Abstract Factory Design Pattern in java

  • Part of structural design pattern.
  • Making an existing class adapt as with the feature of an interface

Already present class which needs to adapted :

public class MarkerPen {
	public void mark(String text) {
		System.out.println("Marking with Marker : "+text);
	}
}

The Interface which we need to implement :

public interface Pen {
	void write(String text);
}

The Adapter Class which will adapt MarkerPen to work with Pen Interface :

public class MarkerPen {
	public void mark(String text) {
		System.out.println("Marking with Marker : "+text);
	}
}

Actual class which is going to use the Pen :

public class AssignmentWork {
	Pen p;
	public void setP(Pen p) {
		this.p = p;
	}
	public void writeAssignment(String text) {
		p.write(text);
	}
}

Main class :

public class AdapterDemo {
	public static void main(String[] args) {
		Pen pen= new PenAdapter();
		AssignmentWork assignmentWork = new AssignmentWork();
		assignmentWork.setP(pen);
		assignmentWork.writeAssignment("Hello Adapter Class");
	}
}

Leave a Comment