工厂方法模式

来源:互联网 发布:国家实行网络什么战略 编辑:程序博客网 时间:2024/06/07 22:47
/** * @version 0.1 */public interface Type {    void show();}


/** * @version 0.1 */public class Circle implements Type {    @Override    public void show() {        System.out.println("This is a circle type.");    }}

/** * @version 0.1 */public class Rectangle implements Type {    @Override    public void show() {        System.out.println("This is a rectangle type.");    }}

/** * 普通工厂模式下,调用工厂中的生产方法,通过字符串匹配方式生产相应实例 * @version 0.1 */public class TypeFactory {    public Type getType(String type){        if(type.equals("circle")){            return new Circle();        }else if(type.equals("rectangle")){            return new Rectangle();        }        return null;    }}

/** * @version 0.1 */public class Test {    public static void main(String[] args) {                TypeFactory factory = new TypeFactory();        Type circle = factory.getType("circle");        Type rectangle = factory.getType("rectangle");                circle.show();        rectangle.show();    }}

/** * 多个工厂方法模式:在工厂中对不同的生产对象添加不同的生产方法, * 调用时直接返回相应的实例,避免传入字符串和字符串匹配操作 * @version 0.1 */public class TypeFactory {    public Type getCircle() {        return new Circle();    }    public Type getRectangle(){        return new Rectangle();    }}

/** * @version 0.1 */public class Test {    public static void main(String[] args) {                TypeFactory factory = new TypeFactory();        Type circle =  factory.getCircle();        Type rectangle = factory.getRectangle();                circle.show();        rectangle.show();    }}

/** * 静态的工厂方法:将工厂方法设为类方法,调用时无需实例化工厂 * @version 0.1 */public class TypeFactory {    public static Type getCircle() {        return new Circle();    }    public static Type getRectangle(){        return new Rectangle();    }}

/** * @version 0.1 */public class Test {    public static void main(String[] args) {        Type circle =  TypeFactory.getCircle();        Type rectangle = TypeFactory.getRectangle();                circle.show();        rectangle.show();    }}