工厂模式JAVA.ppt

工厂模式JAVA.ppt

ID:49411780

大小:639.00 KB

页数:58页

时间:2020-02-06

工厂模式JAVA.ppt_第1页
工厂模式JAVA.ppt_第2页
工厂模式JAVA.ppt_第3页
工厂模式JAVA.ppt_第4页
工厂模式JAVA.ppt_第5页
资源描述:

《工厂模式JAVA.ppt》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库

1、JAVA工厂模式工厂模式专门负责将大量有共同接口的类实例化。工厂模式可以动态决定将哪一个类实例化,不必事先知道每次要实例化哪一个类。工厂模式的几种形态(1)简单工厂(SimpleFactory)模式,又称静态工厂方法模式(StaticFactoryMethodPattern)。(2)工厂方法(FactoryMethod)模式,又称多态性工厂(PolymorphicFactory)模式或虚拟构造子(VirtualConstructor)模式;(3)抽象工厂(AbstractFactory)模式,又称工具箱(Kit或Toolkit)模式。简单工厂实例比如说有一个农场

2、公司,专门向市场销售各类水果。在这个系统里需要描述下列的水果:葡萄Grape草莓Strawberry苹果Apple水果与其他的植物有很大的不同,就是水果最终是可以采摘食用的。那么一个自然的作法就是建立一个各种水果都适用的接口,以便与农场里的其他植物区分开。代码清单1:接口Fruit的源代码publicinterfaceFruit{/***生长*/voidgrow();/***收获*/voidharvest();/***种植*/voidplant();}代码清单2:类Apple的源代码publicclassAppleimplementsFruit{privatei

3、nttreeAge;publicvoidgrow(){log("Appleisgrowing...");}publicvoidharvest(){log("Applehasbeenharvested.");}publicvoidplant(){log("Applehasbeenplanted.");}publicstaticvoidlog(Stringmsg){System.out.println(msg);}publicintgetTreeAge(){returntreeAge;}publicvoidsetTreeAge(inttreeAge){this.tr

4、eeAge=treeAge;}}代码清单3:类Grape的源代码publicclassGrapeimplementsFruit{privatebooleanseedless;publicvoidgrow(){log("Grapeisgrowing...");}publicvoidharvest(){log("Grapehasbeenharvested.");}publicvoidplant(){log("Grapehasbeenplanted.");}publicstaticvoidlog(Stringmsg){System.out.println(msg);}

5、publicbooleangetSeedless(){returnseedless;}publicvoidsetSeedless(booleanseedless){this.seedless=seedless;}}类Strawberry的源代码publicclassStrawberryimplementsFruit{publicvoidgrow(){System.out.println("Strawberryisgrowing...");}publicvoidharvest(){System.out.println("Strawberryhasbeenharve

6、sted.");}publicvoidplant(){System.out.println("Strawberryhasbeenplanted.");}}FruitGardener类的源代码publicclassFruitGardener{publicstaticFruitfactory(Stringwhich)throwsBadFruitException{if(which.equalsIgnoreCase("apple")){returnnewApple();}elseif(which.equalsIgnoreCase("strawberry")){retu

7、rnnewStrawberry();}elseif(which.equalsIgnoreCase("grape")){returnnewGrape();}else{thrownewBadFruitException("Badfruitrequest");}}}简单工厂模式的结构工厂类(Creator)角色:担任这个角色的是工厂方法模式的核心,含有与应用紧密相关的商业逻辑。工厂类在客户端的直接调用下创建产品对象,它往往由一个具体Java类实现。抽象产品(Product)角色:担任这个角色的类是工厂方法模式所创建的对象的父类,或它们共同拥有的接口。抽象产品角色可以用

8、一个Java接口或者Ja

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。