Design patterns: general repeatable solution to common occuring problems
Define an interface to create an object
public interface Shape { void draw(); }
public class Circle implements Shape {
public void draw() {System.out.println("Drawing a Circle"); }
}
public class Square implements Shape {
public void draw() {System.out.println("Drawing a Square"); }
}
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType.equalsIgnoreCase("CIRCLE"))
return new Circle();
else if (shapeType.equalsIgnoreCase("SQUARE"))
return new Square();
return null;
}
}
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape circleObj = shapeFactory.getShape("CIRCLE");
Shape squareObj = shapeFactory.getShape("SQUARE");
}
}
Factory of factories
construct complex object step by step
public class Pizza {
private String dough, sauce, cheese;
public Pizza(PizzaBuilder builder) {
this.dough = builder.dough; this.sauce = builder.sauce;
}
}
public class PizzaBuilder {
private String dough, sauce, cheese;
public PizzaBuilder(String dough, String sauce) {
this.dough = dough; this.sauce = sauce;
}
public PizzaBuilder addCheese(boolean cheese) {
this.cheese = cheese;
return this;
}
public Pizza build() { return new Pizza(this); }
}
public class BuilderPatternDemo {
public static void main(String[] args) {
Pizza pizza1 = new PizzaBuilder("Thin Crust", "Tomato")
.addCheese(true)
.build();
}
}
converts one interface into another as client expects(just change functionnames).
Behavioral design patterns- Class’s objects communication