Github:FactoryPattern.java
创建接口,定义公共方法
/*** 公共接口*/public interface Shape{void draw();}
创建接口实现类
矩形实现类
/*** 矩形*/public class Rectangle implements Shape{@Overridepublic void draw() {System.out.println("this is Rectangle::draw method!");}}
圆形实现类
/*** 圆形*/public class Circle implements Shape{@Overridepublic void draw() {System.out.println("this is Circle::draw method!");}}
正方形实现类
/*** 正方形*/public class Square implements Shape{@Overridepublic void draw() {System.out.println("this is Square::draw method!");}}
定义形状枚举类
/*** 定义可使用的类型,所有新的在此增加即可*/public enum ShapeEnums{RECTANGLE, CIRCLE, SQUARE;}
创建工厂类
/*** 定义 shape工厂*/public class ShapeFactory{private Shape shape;public ShapeFactory(ShapeEnums shape){switch (shape){case RECTANGLE: this.shape = new Rectangle(); break;case CIRCLE: this.shape = new Circle(); break;case SQUARE: this.shape = new Square(); break;default: throw new IllegalArgumentException("not found match construct method with : "+shape);}}public Shape getShape() {return shape;}}
测试,打印矩形
public static void main(String[] args) {FactoryPattern factoryPattern = new FactoryPattern();factoryPattern.factory();}public void factory(){ShapeFactory factory = new ShapeFactory(ShapeEnums.CIRCLE);factory.getShape().draw();}
输出结果:
this is Rectangle::draw method!
打印其他类型:
只需要创建工厂实例即可。
public void factory(){// 矩形ShapeFactory factory = new ShapeFactory(ShapeEnums.RECTANGLE);factory.getShape().draw();// 圆形factory = new ShapeFactory(ShapeEnums.CIRCLE);factory.getShape().draw();// 正方形factory = new ShapeFactory(ShapeEnums.SQUARE);factory.getShape().draw();}
输出结果:
this is Rectangle::draw method!this is Circle::draw method!this is Square::draw method!
如何新增其他类型
1. 在枚举类新增指定类型
比如新增菱形
/*** 定义可使用的类型,所有新的在此增加即可*/public enum ShapeEnums{RECTANGLE, CIRCLE, SQUARE, RHOMBUS;}
2. 新增菱形实现类
/*** 菱形*/public class Rhombus implements Shape{@Overridepublic void draw() {System.out.println("this is Rhombus::draw method!");}}
3. 修改工厂类,新增菱形实例化
/*** 定义 shape工厂*/public class ShapeFactory{private Shape shape;public ShapeFactory(ShapeEnums shape){switch (shape){case RECTANGLE: this.shape = new Rectangle(); break;case CIRCLE: this.shape = new Circle(); break;case SQUARE: this.shape = new Square(); break;case RHOMBUS: this.shape = new Rhombus(); break;default: throw new IllegalArgumentException("not found match construct method with : "+shape);}}public Shape getShape() {return shape;}}
4. 测试
public void factory(){// 矩形ShapeFactory factory = new ShapeFactory(ShapeEnums.RECTANGLE);factory.getShape().draw();// 圆形factory = new ShapeFactory(ShapeEnums.CIRCLE);factory.getShape().draw();// 正方形factory = new ShapeFactory(ShapeEnums.SQUARE);factory.getShape().draw();// 菱形factory = new ShapeFactory(ShapeEnums.RHOMBUS);factory.getShape().draw();}
输出结果:此时会发现多了打印菱形结果
this is Rectangle::draw method!this is Circle::draw method!this is Square::draw method!this is Rhombus::draw method!
