简单工厂模式

导读:本篇文章讲解 简单工厂模式,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一. 定义

       简单工厂其实并不是一个设计模式,说它是一种良好的编程规范更为合适。它将创建对象的代码和业务逻辑的代码相互隔离开来,增加了程序的松耦合效果。

二. 模式起源

三. 设计原则

       
封装变化。

四. UML图

简单工厂模式

五. 代码

5.1 水果类

package model.simpleFactory;

/**
 * 水果类
 */
public abstract class Fruit {

    /**
     * 展示是哪种水果
     */
    public abstract void show();

}

5.2 苹果水果类

package model.simpleFactory;

/**
 * 水果:苹果
 */
public class Apple extends Fruit {

    @Override
    public void show() {
        System.out.println("i am a apple");
    }
}

5.3 香蕉水果类

package model.simpleFactory;

/**
 * 水果: 香蕉
 */
public class Banana extends Fruit {

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

5.4 橘子水果类

package model.simpleFactory;

/**
 * 水果: 橙子
 */
public class Orange extends Fruit {

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

5.5 梨水果类

package model.simpleFactory;

/**
 * 水果: 梨
 */
public class Pear extends Fruit {

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

5.6 简单水果工厂类

package model.simpleFactory;

/**
 * 简单水果工厂
 */
public class SimpleFruitFactory {

    /**
     * 创建水果
     *
     * @param type 类型
     * @return Fruit
     */
    public static Fruit createFruit(String type) {

        Fruit fruit = null;

        if (type.equals("apple")) {
            fruit = new Apple();
        } else if (type.equals("banana")) {
            fruit = new Banana();
        } else if (type.equals("orange")) {
            fruit = new Orange();
        } else if (type.equals("pear")) {
            fruit = new Pear();
        }

        return fruit;
    }

}

5.7 水果商店类

package model.simpleFactory;

/**
 * 水果商店
 */
public class FruitStore {

    /**
     * 内部维护一个简单水果工厂
     */
    private SimpleFruitFactory factory;

    public FruitStore(SimpleFruitFactory factory) {
        this.factory = factory;
    }

    public Fruit orderFruit(String type) {

        Fruit fruit = SimpleFruitFactory.createFruit(type);

        fruit.show();

        return fruit;
    }


}

5.8 测试

package model.simpleFactory;

public class Main {

    public static void main(String[] args) {

        SimpleFruitFactory simpleFruitFactory = new SimpleFruitFactory();
        FruitStore fruitStore = new FruitStore(simpleFruitFactory);

        fruitStore.orderFruit("apple");

        fruitStore.orderFruit("banana");

    }

}

5.9 结果

i am a apple
I am a banana

六. 感悟

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/17810.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!