学习笔记之简单工厂设计模式

工厂设计模式:根据一定的逻辑来负责对象的生产。

简单工厂设计模式:又称为静态工厂方法模式,由一个工厂类,根据传人的参数决定生产哪一种对象

三种角色:工厂角色,抽象产品角色,具体产品角色

故事:水果农场生产水果(苹果和香蕉),一个顾客直接去农场买水果

首先抽象角色:

水果接口

public interface IFruit {
    void growth();
}

具体产品角色:苹果,香蕉

public class Apple implements IFruit {

    public void growth() {
        System.out.println("变红了");
    }

}
public class Banana implements IFruit {

    public void growth() {
        System.out.println("变黄了");
    }

}

工厂角色:

public class FruitFarm {
    public static IFruit pickUp (String fruitName) throws NoSuchFruitException{
        if("Apple".equals(fruitName)){
            return new Apple();
        }else if("Banana".equals(fruitName)){
            return new Banana();
        }else {
            throw new NoSuchFruitException("没有您要的"+fruitName);//如果没买到就抛出自定义异常
        }
    }
}

然后顾客去农场买水果:

public class Customer {
    public void buy(){
        try {
            IFruit fruit = FruitFarm.pickUp("Banana");
            fruit.growth();
        } catch (NoSuchFruitException e) {
            System.out.println("不吃了,算了"+e);
        }
    }
    
    public static void main(String[] args) {
        Customer customer = new Customer();
        customer.buy();
    }
}


控制台打印:

变黄了

原文地址:https://www.cnblogs.com/hnzyyTl/p/4909050.html