工厂模式

    xiaoxiao2021-04-15  183

    工厂模式

    欢迎关注公众号:**一盐难进**

    在开发的过程中,当我们有大量公共接口的类需要实例化,而且事先不知道要实例化哪一个类的时候,就可以使用工厂模式了,它会创建一个用来创建目标接口对象的工厂接口,然后由工厂接口的实现类去决定去实例化哪一个类。

    代码实现:

    /** * 水果接口 */ public interface Fruit { //定义两个抽象方法 void buyFruit(); void eatFruit(); } /** * 工厂接口 */ interface FruitFactory { //获取水果抽象方法 Fruit getFruit(); } /** * 香蕉 */ class Banana implements Fruit { public Banana() { } @Override public void buyFruit() { System.out.println("buy banana!"); } @Override public void eatFruit() { System.out.println("eat banana!"); } } /** * 梨 */ class Pear implements Fruit { public Pear() { } @Override public void buyFruit() { System.out.println("buy pear!"); } @Override public void eatFruit() { System.out.println("eat pear!"); } } /** * 香蕉工厂类 */ class BananaFactory implements FruitFactory { @Override public Fruit getFruit() { return new Banana(); } } /** * 梨工厂类 */ class PearFactory implements FruitFactory { @Override public Fruit getFruit() { return new Pear(); } } class FactoryTest{ /** * 消费方法,传入工厂对象 * @param factory */ public static void consume(FruitFactory factory){ //由工厂对象得到水果对象 Fruit fruit = factory.getFruit(); //买水果,吃水果 fruit.buyFruit(); fruit.eatFruit(); } public static void main(String[] args) { //调用消费方法 consume(new BananaFactory()); consume(new PearFactory()); } }

    执行 FactoryTest 中的 main 方法,执行结果如下:

    buy banana! eat banana! buy pear! eat pear!

    上述代码创建了一个 Fruit 接口,接口中有两个抽象方法:buyFruit() 和 eatFruit(),Fruit 接口有两个具体实现类 Banana 和 Pear。然后创建了工厂接口 Factory,接口定义了获取 Fruit 对象的抽象方法,Factory 接口有两个具体工厂类 BananaFactory 和 PearFactory。当调用消费方法 consume() 方法的时候,只需要传入具体的工厂对象即可,由工厂对象来决定消费哪一种水果,然后通过工厂对象得到水果对象,再执行 buyFruit 和 eatFruit。

    通过这种方式,代码将接口和实现完全分离,解耦更充分,同时,在调用 Fruit 的方法的时候,不需要知道 Fruit 的具体类型,通过工厂获取即可,如果需要增加新的水果,只需要加一个新的水果类和对应的工厂类,不需要对原来的代码做任何修改。

    欢迎关注公众号:一盐难进


    最新回复(0)