设计模式实验.docxVIP

  • 700
  • 0
  • 约 32页
  • 2017-02-08 发布于重庆
  • 举报
设计模式实验

《代码重构与设计模式》课堂实验徐海蛟博士 2016.03实验一工厂模式的应用【实验目的】1)掌握工厂模式(Factory)的特点2)分析具体问题,使用工厂模式进行设计。【实验内容和要求】有一个 OEM制造商代理做 HP笔记本电脑(Laptop),后来该制造商得到了更多的品牌笔记本电脑的订单 Acer、Lenovo、Dell,该 OEM商发现,如果一次同时做很多个牌子的本本,有些不利于管理。利用工厂模式改善设计,用控制台应用程序实现该 OEM制造商的工厂模式。该模式的 UML图如下。【模式UML图】【模式代码(JAVA语言实现)】publicclass FactoryMethod {// 主类publicstaticvoid main(String[] args) { Computer c; Factory f = new DellFactory(); c = f.getComputerType(); c.ComputerType(); f = new LenovoFactory(); 1《代码重构与设计模式》课堂实验徐海蛟博士 2016.03c = f.getComputerType(); c.ComputerType(); f = new AcerFactory(); c = f.getComputerType(); c.ComputerType(); } } interface Factory{ Computer getComputerType(); } class DellFactoryimplements Factory{ @Overridepublic Computer getComputerType() { returnnew Dell(); } } classAcerFactory implements Factory{ @Overridepublic Computer getComputerType() { returnnew Acer(); } } class LenovoFactory implements Factory{ @Overridepublic Computer getComputerType() { returnnew Lenovo(); } } /** * 电脑品牌 */interface Computer{ publicvoid ComputerType(); } class Dell implements Computer{ @Overridepublicvoid ComputerType() { // TODO Auto‐generated method stub2《代码重构与设计模式》课堂实验徐海蛟博士 2016.03System.out.println(Dell Computer); } } class Acer implements Computer{ @Overridepublicvoid ComputerType() { System.out.println(Acer Computer); } } class Lenovo implements Computer{ @Overridepublicvoid ComputerType() { // TODOAuto‐generated method stubSystem.out.println(Lenovo Computer); } } 【运行截图】【实验小结】通过本次实验,学会了使用工厂方法模式。工厂方法模式的适用性如下:当一个类不知道它所必须创建的对象的类时。当一个类希望由它的子类来指定它所创建的对象时。当类将创建对象的职责委托给多个帮助子类中的某一个,并且希望将哪一个帮助子类是代理这一信息局部化时。3《代码重构与设计模式》课堂实验徐海蛟博士 2016.03实验二抽象工厂模式的应用【实验目的】1)掌握抽象工厂模式(Abstract Factory)的特点2)分析具体问题,使用抽象工厂模式进行设计。【实验内容和要求】麦当劳(McDonalds)和肯德基(KFC)快餐店都经营汉堡(Hamburg)和可乐(Cola),用 JAVA控制台应用程序实现这两个快餐店经营产品的抽象工厂模式。该模式的 UML图如下。【模式 UML 图】【模式代码】publicclass AbstractFactoryTest { publicstaticvoid main(String[] args) { Hamburg h; Cola c; AbstractFactory af = new MDNFactory(); 4《代码重构与设计模式》课堂实验徐海蛟博士 2016.03h = af.createHamburg(); c = af.createCo

文档评论(0)

1亿VIP精品文档

相关文档