标签:扩展性 img 实例化 dem ring rectangle pre col alt
工厂方法模式定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行
类图:
1 package pattern; 2 3 public interface Shape { 4 void draw(); 5 }
1 package pattern; 2 3 public class Rectangle implements Shape{ 4 @Override 5 public void draw() { 6 System.out.println("draw rectangle"); 7 } 8 }
1 package pattern; 2 3 public class Square implements Shape { 4 @Override 5 public void draw() { 6 System.out.println("draw square"); 7 } 8 }
1 package pattern; 2 3 public class Circle implements Shape { 4 @Override 5 public void draw() { 6 System.out.println("draw circle"); 7 } 8 }
1 package pattern; 2 3 public class ShapeFactory { 4 public Shape getShape(String shape) { 5 if ("circle".equals(shape)) { 6 return new Circle(); 7 } else if ("rectangle".equals(shape)) { 8 return new Rectangle(); 9 } else if ("square".equals(shape)) { 10 return new Square(); 11 } 12 return null; 13 } 14 }
1 package pattern; 2 3 public class FactoryPatternDemo { 4 public static void main(String[] args) { 5 ShapeFactory shapeFactory = new ShapeFactory(); 6 7 Shape shape1 = shapeFactory.getShape("circle"); 8 shape1.draw(); 9 10 Shape shape2 = shapeFactory.getShape("rectangle"); 11 shape2.draw(); 12 13 Shape shape3 = shapeFactory.getShape("square"); 14 shape3.draw(); 15 } 16 } 17 /* 18 draw circle 19 draw rectangle 20 draw square 21 */
工厂方法模式的好处:
1. 一个调用者想创建一个对象,只要知道其名称就可以了
2. 扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以
3. 屏蔽产品的具体实现,调用者只关心产品的接口
标签:扩展性 img 实例化 dem ring rectangle pre col alt
原文地址:https://www.cnblogs.com/sakura1027/p/9233850.html