欢迎来到天天文库
浏览记录
ID:40296164
大小:90.00 KB
页数:8页
时间:2019-07-30
《09_工厂和单例模式_思路与案例》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、简单工厂模式农场(FruitGardener)生产的水果(Fruit)有三种:葡萄(Grape)、苹果(Apple)和草莓(Strawberry)publicinterfaceFruit{publicvoidplan();publicvoidgrow();publicvoidharvest();}publicclassAppleimplementsFruit{publicvoidgrow(){System.out.println("苹果在生长...");}}publicclassGrapeimplementsFruit{publicvo
2、idgrow(){System.out.println("葡萄在生长...");}}publicclassStrawberryimplementsFruit{publicvoidgrow(){System.out.println("草莓在生长...");}}publicclassFruitGardener{publicstaticFruitcreateFruit(Stringname){if("apple".equals(name)){returnnewApple();}if("grape".equals(name)){returnne
3、wGrape();}if("strawberry".equals(name)){returnnewStrawberry();}returnnewApple();}}publicclassTest{publicstaticvoidmain(String[]args){FruitGardener.createFruit("apple").plan();FruitGardener.createFruit("grape").grow();FruitGardener.createFruit("strawberry").grow();}}随着业务的
4、扩大,农场生产的果品种类越来越多,按照原有的模式,由一个农场生产所有种类的水果,导致任务过重、判断过多,逻辑过于复杂,容易出错,难于管理,牵一发而动全身,增加新品种困难,需要改进设计模式,适应于新的情况。工厂方法模式将农场分为若干种:苹果农场负责生产苹果、草莓农场负责生产草莓、葡萄农场负责生产葡萄publicinterfaceFruit{//抽象的产品publicvoidgrow();}publicinterfaceFruitFactoy{//抽象的工厂publicFruitcreateFruit();}publicclassApple
5、implementsFruit{//具体的产品publicvoidgrow(){System.out.println("苹果在生长...");}}publicclassGrapeimplementsFruit{//具体的产品publicvoidgrow(){System.out.println("葡萄在生长...");}}publicclassStrawberryimplementsFruit{//具体的产品publicvoidgrow(){System.out.println("草莓在生长...");}}publicclassAppl
6、eFactoryimplementsFruitFactoy{//具体的工厂publicFruitcreateFruit(){returnnewApple();}}publicclassGrapeFactoryimplementsFruitFactoy{//具体的工厂publicFruitcreateFruit(){returnnewGrape();}}publicclassStrawberryFactoryimplementsFruitFactoy{//具体的工厂publicFruitcreateFruit(){returnnewStr
7、awberry();}}publicclassTest{publicstaticvoidmain(String[]args){newAppleFactory().createFruit().grow();newGrapeFactory().createFruit().grow();newStrawberryFactory().createFruit().grow();}}随着市场和企业定位变化,决定只生产苹果、葡萄和草莓等少数果品,但每一果品呈系列化,如:普通水果、绿色水果等等,原设计模式不能很好地适应这种需要,需要改进设计模式。抽象工
8、厂模式农场分为两种:普通农场生产各种普通水果,绿色农场生产各种绿色水果。publicinterfaceFruit{//抽象的水果产品publicvoidgrow();}publicinterfaceFrui
此文档下载收益归作者所有