Java 设计模式——工场模式(Factory method)

来源:互联网 发布:陈浩民 妻子 知乎 编辑:程序博客网 时间:2024/06/06 03:21

工场模式:通过一个公共接口来将 对象的创建逻辑与用户分离。

例子:

创建一个ShapeFactory获得不同的Shape对象(Circle,Rectangle,Square)

第一步:创建接口Shape.java

public interface Shape {void draw();}

第二步:创建具体的类来实现接口
Rectangle.java
public class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Inside Rectangle::draw() method.");}}

Rectangle.java
public class Square implements Shape {@Overridepublic void draw() {System.out.println("Inside Square::draw() method.");}}

Circle.java
public class Circle implements Shape{@Overridepublic void draw() {System.out.println("Inside Circle::draw() method.");}}

第三步:创建工场类ShapeFactory.java,根据用户传入的信息获得对应的类的实例

public class ShapeFactory {public Shape getShape(String shapeType){if(shapeType == null){return null;}if(shapeType.equalsIgnoreCase("CIRCLE")){return new Circle();}if(shapeType.equalsIgnoreCase("RECTANGLE")){return new Rectangle();}if(shapeType.equalsIgnoreCase("SQUARE")){return new Square();}return null;}}


第四步:使用工场类测试 FactoryPatternDemo.java


public class FactoryPatternDemo {public static void main(String[] args) {ShapeFactory shapeFactory = new ShapeFactory();Shape shape1 = shapeFactory.getShape("CIRCLE");shape1.draw();Shape shape2 = shapeFactory.getShape("RECTANGLE");shape2.draw();Shape shape3 = shapeFactory.getShape("SQUARE");shape3.draw();}}


输出结果:

Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.


0 0
原创粉丝点击