博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
学习笔记之简单工厂设计模式
阅读量:6995 次
发布时间:2019-06-27

本文共 1202 字,大约阅读时间需要 4 分钟。

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

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

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

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

首先抽象角色:

水果接口

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

你可能感兴趣的文章