工厂模式(Factory Pattern)
1,Shape接口的定义
package factory; public interface Shape { void draw(); }
2,Circle实现Shape接口
package factory; public class Circle implements Shape { @Override public void draw() { System.out.println("draw a Circle"); } }
3,Rectangle实现Shape接口
package factory; public class Rectangle implements Shape { @Override public void draw() { System.out.println("draw a rectangle"); } }
4,Square实现Shape接口
package factory; public class Square implements Shape { @Override public void draw() { System.out.println("draw a Square"); } }
5,工厂方法类ShapeFactory
package factory; public class ShapeFactory { static final String CIRCLE="circle"; static final String SQUARE="square"; static final String RECTANGLE="rectangle"; public Shape getShape(String type){ if(type.equals(CIRCLE)){ return new Circle(); }else if(type.equals(RECTANGLE)){ return new Rectangle(); }else if(type.equals(SQUARE)){ return new Square(); }else{ return null; } } }
6,工厂的使用Demo
package factory; public class FactoryDemo { public static void main(String[] args) { ShapeFactory factory= new ShapeFactory(); Shape shape=factory.getShape(ShapeFactory.CIRCLE); shape.draw(); } }