设计模式(二)——工厂模式

2018-08-16  本文已影响9人  沧海一粟谦

简单工厂模式又叫做静态工厂方法模式,是常用的实例化对象模式。

抽象产品类:工厂类所创建对象的父类

public interface IFruit {
    void get();
}

具体产品类:工厂类创建的具体对象

public class Apple implements IFruit {

    @Override
    public void get() {
        System.out.println("I am a apple.");
    }
}
public class Orange implements IFruit {

    @Override
    public void get() {
        System.out.println("I am a orange." );
    }
}

工厂类:工厂类包含了负责创建所有实例具体逻辑;可以直接被外界调用来创建所需要的对象

public class FruitFactory {

    public static IFruit getFruit(String type) {

        IFruit ifruit = null;
        if ("apple".equals(type)) {
            ifruit = new Apple();
        } else if ("orange".equals(type)) {
            ifruit = new Orange();
        }
        return ifruit;
    }
}

测试

public static void main(String[] args) {

        IFruit apple = FruitFactory.getFruit("apple");
        IFruit orange = FruitFactory.getFruit("orange");

        apple.get();
        orange.get();
    }
I am a apple.
I am a orange.

总结

上一篇下一篇

猜你喜欢

热点阅读