Java 工厂模式

2021-02-09  本文已影响0人  索性流年

文集地址

一句话总结工厂模式

概述

工厂模式分类

应用场景小案例

实现案例

/**
 * 生产水果接口
 *
 * @author liunian
 * @date 2021/2/5 17:15
 */
public interface FruitsCompany {
    /**
     * 生产水果
     */
    void sendFruits();
}

/**
 * 生产香蕉
 * @author liunian
 * @date 2021/2/5 17:22
 */
public class BananaFruits implements FruitsCompany {
    @Override
    public void sendFruits() {
        System.out.println("生产香蕉");
    }
}

/**
 * 生产苹果
 * @author liunian
 * @date 2021/2/5 17:15
 */
public class appleFruits implements FruitsCompany {
    @Override
    public void sendFruits() {
        System.out.println("生产苹果");
    }
}

简单工厂


/**
 * @author liunian
 * @date 2021/2/5 17:24
 */
public class FruitsCompanyFactory {

    /**
     * 生产水果
     * @param type 水果类型
     */
    public FruitsCompany produceFruit(String type){
        switch (type){
            case "apple":
                return new appleFruits();
            case "banana":
                return new BananaFruits();
            default:
                return null;
        }
    }

}

/**
 * @author liunian
 * @date 2021/2/5 17:27
 */
public class FactoryApp {
    public static void main(String[] args) {
        FruitsCompanyFactory fruitsCompanyFactory = new FruitsCompanyFactory();
        FruitsCompany apple = fruitsCompanyFactory.produceFruit("apple");
        apple.sendFruits();
        FruitsCompany banana = fruitsCompanyFactory.produceFruit("banana");
        banana.sendFruits();
    }
}

工厂方法


/**
 * @author liunian
 * @date 2021/2/5 17:24
 */
public class FruitsCompanyFactory02 {

    /**
     * 生产苹果
     *
     * @return 苹果工厂
     */
    public FruitsCompany produceApple() {
        return new appleFruits();
    }

    /**
     * 生产香蕉
     *
     * @return 香蕉工厂
     */
    public FruitsCompany produceBanana() {
        return new BananaFruits();
    }


}

/**
 * @author liunian
 * @date 2021/2/5 17:27
 */
public class FactoryApp {

    public static void main(String[] args) {
        FruitsCompanyFactory02 fruitsCompanyFactory02 = new FruitsCompanyFactory02();
        FruitsCompany apple = fruitsCompanyFactory02.produceApple();
        apple.sendFruits();
        FruitsCompany banana = fruitsCompanyFactory02.produceBanana();
        banana.sendFruits();
    }
}
上一篇下一篇

猜你喜欢

热点阅读