简单工厂模式(Simple Factory Pattern)
定义
简单工厂模式又称为静态工厂方法模式(Static Factory Method Pattern)定义一个类,根据参数的不同返回不同类的实例,这些类具有公共的父类和一些公共的方法。简单工厂模式不属于 GoF设计模式(《Design Patterns: Elements of Reusable Object-Oriented Software》(即后述《设计模式》一书),由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides 合著(Addison-Wesley,1995)。这几位作者常被称为"四人组(Gang of Four)"。),它是最简单的工厂模式
UML(universal modeling language)图
简单工厂模式实例之 图形工厂
UML图
下面贴代码
1 interface Shape { 2 void draw(); 3 void erase(); 4 }
1 public class Cricle implements Shape { 2 3 @Override 4 public void draw() { 5 // TODO Auto-generated method stub 6 System.out.println("绘制圆形!"); 7 } 8 9 @Override 10 public void erase() { 11 // TODO Auto-generated method stub 12 System.out.println("擦除圆形!"); 13 } 14 }
1 public class Rectangle implements Shape{ 2 3 @Override 4 public void draw() { 5 // TODO Auto-generated method stub 6 System.out.println("绘制矩形!"); 7 } 8 9 @Override 10 public void erase() { 11 // TODO Auto-generated method stub 12 System.out.println("擦除矩形!"); 13 } 14 15 }
1 public class Triangle implements Shape{ 2 3 @Override 4 public void draw() { 5 // TODO Auto-generated method stub 6 System.out.println("绘制三角形!"); 7 } 8 9 @Override 10 public void erase() { 11 // TODO Auto-generated method stub 12 System.out.println("擦除三角形!"); 13 } 14 15 }
1 public class UnspportedShapeException extends Exception{ 2 3 public UnspportedShapeException(String message) { 4 super(message); 5 } 6 7 }
1 public class ShapeFactory{ 2 3 public static Shape createShape(String type) throws UnspportedShapeException { 4 switch (type) { 5 case "cricle": 6 return new Cricle(); 7 case "rectangle": 8 return new Rectangle(); 9 case "triangle": 10 return new Triangle(); 11 default: 12 throw new UnspprotedShapeException(type); 13 } 14 } 15 }
1 public class Client { 2 public static void main(String[] args) { 3 try { 4 Shape s; 5 ShapeFactory sf = new ShapeFactory(); 6 7 s = sf.createShape("cricle"); 8 s.draw(); 9 s.erase(); 10 11 s = sf.createShape("dog"); 12 s.draw(); 13 s.erase(); 14 } catch (UnspportedShapeException e) { 15 // TODO: handle exception 16 System.out.println("没有"+e.getMessage()+"图形"); 17 } 18 } 19 }
运行结果
总结
优点
- 客户端可以不用创建产品对象,而仅仅 消费 产品。
- 简单工厂模式实现了责任的划分
缺点
- 因为工厂集中了所有产品创建逻辑,一旦工厂奔溃停止运作,整个系统都要瘫痪
- 扩展系统困难,如果要更新产品,就违背了开闭原则
2018-03-17 22:47:00 卒