public interface Shape { void draw(); } public class Rectangle: Shape { public void draw() { System.out.println("Inside Rectangle::draw() method."); } } public class Square: Shape { public void draw() { System.out.println("Inside Square::draw() method."); } }
2.为颜色创建接口,创建实现接口的实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public interface Color { void draw(); } public class Red: Color { public void draw() { System.out.println("Inside Red::draw() method."); } } public class Green: Color { public void draw() { System.out.println("Inside Green::draw() method."); } }
3.为 Color 和 Shape 对象创建抽象类来获取工厂。AbstractFactory
public abstract class AbstractFactory { abstract Color getColor(String color); abstract Shape getShape(String shape) ; } 4.创建扩展了 AbstractFactory 的工厂类,基于给定的信息生成实体类的对象。