设计模式实验报告(优选.)_第1页
设计模式实验报告(优选.)_第2页
设计模式实验报告(优选.)_第3页
设计模式实验报告(优选.)_第4页
设计模式实验报告(优选.)_第5页
已阅读5页,还剩50页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、楕品Word.最新文件仅供参考已换word文本方便更改赠人玫瑰,手留余香。实验一单例模式的应用1实验目的1) 掌握单例模式(Singleton )的特点2) 分析具体问题,使用单例模式进行设计。2实验内容和要求很多应用项目都有配置文件,这些配置文件里面定义一些应用需要的参数数据。AppConfig -ParameterA : string +GetParameterA() +SetParameterA()通常客户端使用这个类是通过new 个AppConfig的实例来得到一个操作 配置文件内容的对象。如果在系统运行中,有很多地方都需要使用配置文件的 内容,系统中会同时存在多份配置文件的内容,这会

2、严重浪费内存资源。事实上,对于AppConfig类,在运行期间,只需要一个对象实例就够了。 那么应该怎么实现呢?用C#控制台应用程序实现该单例模式。绘制该模式的UML 图。10/473模式结构图4 UML类图5代码Singleton-instance : Singleton-Si ngletonO十Getlnslance() : SingletonAppconfig-parameterAistringconfig: Appconfig Appco nfig() +-Getlnstance() GetParameterAQ +SetParameterA()class AppConfigpriva

3、te st at ic AppConfig config: private st ring paranie-terA;private AppConfig()public string ParapeterAget return parameterA; set parameterA. = value : public st at i c AppConf ig Get Instance() if (null = config)config = new AppConfig():return config;class Prograjnstatic void Main (string args)AppCo

4、nfig appconfigl = AppConf igGetInsi:ariceC); appconf igl. Parente ter A 二"ParaA."Console. Writ eLineappconfigl:"):Console. Writ eLine(appconfigl ParametarA):AppConfig appconfigZ = AppConf ig.Ge:Console. Writ eLine Cappconf ig2:"):Console. Writ eLine (appconf ig2 Paraniet&rA):

5、Console. Read.():6运行结果材匍包侶网各种课程/设计.Le?I回IMappconfigl:>-I_nParaAuappconfig2:ParaA.实验二工厂模式的应用1实验目的1) 掌握工厂模式(Factory )的特点2) 分析具体问题,使用工厂模式进行设计。2实验内容和要求有一个OEM制造商代理做HP笔记本电脑(Laptop),后来该制造商得到了 更多的品牌笔记本电脑的订单Acer , Lenovo , Dell ,该OEM商发现,如果一 次同时做很多个牌子的本本,有些不利于管理。利用工厂模式改善设计,用C# 控制台应用程序实现该OEM制造商的工厂模式。绘制该模式的U

6、ML图。3模式结构图ConcreteCreator FacioryMelhodO : Product4 UML类图5代码class Laptopprotacted string bHand:public string Brandget return biand: set brand. = value: class HPLaptop : Lap!oppublic HPLaptop()this.btand 二"HP":class AcerLap-top : Laptoppublic AcerLapt op()this .brand = "Acer":clas

7、s LenovoLaptop : Laptop public LenovoLaptop()this, brand = ,vLenovo ; class DellLaptop : Laptoppublic D&LILaptop()this .brand = "Dell":interface LaptopFactoiryL apt op Great eLapt op():class HPLaptopFactory : LaptopFactorypublic Laptop CreateLaptop()return new HPLapt op ():class AcerLa

8、pt opFactofy : LaptopFact orypublic Lapt op Cr eat eL apt op ()return new AcerLaptop ():class LenovoLaptopFactory : LaptopFactorypublic Laptop CresteLapt op ()return n&w LenovoLapt op():class DellLaptopFactory : LaptopFactorypublic Laptop Creat eLapt op ()return n&vr DellLapt op ():class Pro

9、granist atic void Main (st ring args)LaptopFactory HPfactory = new HPLaptopFactory(): LaptopFactoiry Acerfact ory = new AcerLapt opFact ory (): I.-ap-t opFact ory Lenovof act ory = new LenovoLapt opFact ory (): LaptopFactoiry Dellfact ory = new DellLapt opFact ory ():Console叩rit&Lirbe (HPf act o

10、ry CreateLapt op (). Brand): Console WriteLine(Acerfactory CreateLapt op () Brand): Console AVritgLirve (Lenovof actory GreateLaptod () Brand): Console WriteLine(Dellfactory CreateLapt op () Brand):ConsoleRead():6运行结果实验三抽象工厂模式的应用1实验目的1)拿握抽象工厂模式(Abstract Factory )的特点2)分析具体问题,使用抽象工厂模式进行设计。2实验内容和要求麦当劳(

11、McDonalds )和肯德基(KFC )快餐店都经营汉堡(Hamburg )和 可乐(Cola ),用C#控制台应用程序实现这两个快餐店经营产品的抽象工厂模 式。绘制该模式的UML图。3模式结构图齐壬WORD.4 UML滋圈MCDOnaEs+GreareHafnbcrg9 lHamburg +cre%ecocr<?now八 Anterfacevv Noshery wKM+CreareHarrbLrgO 二 Hamburg+Creacecol30"noEF楕品Word.class Hamburgprivate irrt id;private double price;publi

12、c int Idget return id: set id = value: public double Priceget return price: set price = value: interface IHajaburgHannburg Get Hamburg (int id): void UpdateHamburgPrice(int id);class McDonaldsHamburg : IHam.b-urg 'public Hamburg GetHamburg(int id)Conso 1 e. Writ eLine C MMcDonalds买了 一个Hamburg&qu

13、ot;): return null;public void UpdateHniburgPrice(int id)Console. Writ eLine (ffMcDonalds快翳店的HajriLurgP 价大甩卖 了"); 55/47class KFCHamburg : IHamburgpublic Hamburg GetHajriburg (int id)Console. WriteLin& (" MKFC买 了 一个Haniburg"):return null:public void UpdateHajriburgPrics(irrt id)Cons

14、ole. Wr it eLine ("KFC 快霧止的 H amburgP 价大用卖了 '):class Colaprivate int id;private double price;public int Idget return id; set id = value; 1public double Priceget wturn price; set price = value: interface IColaCola GetCola(int id):void UpdateColaPr ice (int id):class NcDonaldsCola : IColapubl

15、ic Cola GetCola(int id)Console. Writ eLine C MMcDonalds 7 个Coir): return null;public void UpdateColoPrice(int id)Cons ole. Writ eLine C McDonsilds快餐隹的Co 1 z眸价大甩卖了"): class KFCCola : IColapublic Cola GetCola(int id)Console. Writ eLine("从KFC买 了 一个Cob"): return null:public void UpdateCol

16、aPrice(int id)Console. Writ eLine ("KFC快辍店的QolaB幸价夭甩卖:/快後店interface NosheryIHamburg Cr eateHaniburg ();ICola CreateColaO :class McDonalds : Mosherypublic IHajuburg CreateHomburg ()wturri new McDonaldsHajnb-urg ();public ICola GreateColaO“tum new McDonaldsCola ():class KFC : No sherypublic IHaju

17、burg CreateHamburg () return, new KFCHamburg ():public ICola CreateColaOwtum new KFCCola():class Programst at ic void Main (string args)Woshery noshery = new KFC ():IHamburg ih = noshery Crat eHambiiirg:(): ih. GetHamburg (1):ih.UpdateHamburgPrice(1):ICola ic = nosheryCHeatgCola():ic.GetCola (1):ic.

18、 Updat eColaPrice(1):Console Read():6运行结果实验四建造者模式的应用1实验目的1) 掌握建造者模式(Builder )的特点2) 分析具体问题,使用建造者模式进行设计。2实验内容和要求建造者模式是一种创建型模式,它主要是应对项目中一些复杂对象的创建 工作。所谓"复杂对象",是指此对象中还含有其它的子对象。我们现在定义一 个场景:汽车生产必须包含车轮(Wheel)、油箱(OilBox)和车身(Body),应用建 造者模式,用C#控制台应用程序实现该设计,构建BMW品牌和BenZ品牌汽 车生产。绘制该模式的UML图。3模式结构图Pr-oduc

19、: t4 UML类图5代码class Cojnponeniprotec七&(1 string name ;public st r ing Nameget return name: set name = value; class We el : Componentpublic We el ()七hisname = "Wheel":class OUBqk ; Componentpublic OilBoxOt his .name = "OiUBox":class CarBody : Componentpublic CarBody() this.nan&

20、amp; = "CstrBody":class Carprivat e IList < Comp orient > parts = new List <Cojnpon.eni: > ():public void Add(Component component)part s. Add (c omponent):public void Show()for each (C ojnp orient component in parts)Console申工iteLine (component Najne):abst ract class CarBuxlcLer

21、public abst ract void BuildV/ltccl ();public abst ract void BuildOiIBok():public abst rac七 voi d BuildCarBodyO :public abst ract 匚ar GetCarO :class BrifWBuilder : CarBuilderprivate Car car = new Car ():public override void Build/heelOcar Add (nev V/heel ():public override void BuildOilBoxOcarAcLd(ne

22、即 OilBox ():public override void BuildCarBody()carAtLd(ne即 CarBody();public override Car GetCar()return car;class BenZBuilder : CarBuilderprivate Car car = new Car ():public override void BuildWeelOcar. Add (new Weel ():public override void BuildOilBox()car. Add (new OilBox ();public override void B

23、uildCarBodyOcar. Add (new CarBodyO );public override Car GetCar ()return car:class CarDirectorpublic void BuildCr(CarBuilder c*b) cb. BuildV/heel ():cb BuildOilBox ():cb BuildCarBody ():class Programst at i c void Main (st ring args)CarDirect or direct or = new CarDirector(); CarBuilder cbl = new BJ

24、ifBuilder (); CarBuilder cb2 = new BenZBuilder();Console. Writ eLine CfBuild BW“);dixector.BuildCar(cbl);Car carl = cbl. GetCar ():carl. Show():Console. WriteLine CBuild BenZA,):director BuildCar(cb2):Car car2 = cb2 GetCai:():car2 Show ():Console ReadO :6运行结果 file:/E:/4.&. " L貝Build BMWUhee

25、lOilBoxCarBodyBuxld BenZUheelOilBoxCarBodsr4 实验五适配器模式的应用1实验目的1) 掌握适配器模式(Adapter )的特点2) 分析具体问题,使用适配器模式进行设计。2实验内容和要求个软件团队开发绘图系统,设计了圆对象(Circle).矩形对象 (Rectangle),线对象(Line)都支持Draw()函数,即可以通过Draw()函数绘制图 形。为了加快项目进度,将角度对象(Angle)绘制功能交给了合作团队实现。但 合作团队将角度对象绘制函数定为了 DrawAngle()o绘图系统提供给用户后,用 户不满意,希望能统一的调用,不用记太多命令。应

26、用适配器模式,用C#控制 台应用程序完善该设计。绘制该模式的UML图。3模式结构图4 UML类图5代码abstract class Graphics public abstract void DrawO :class Circle : Graphicspublic override void Draw()Console. Vr it eLine了一个圆");class Rectangle : Graphics public override void DravO Console. Writ eLine ("131 "7 个矩形"): class Line

27、 : Graphics public override void DrawO Console. Writ eLine ("画 了 一条直线"): class Anglepublic void DrawAngle()Console. Writ eLine ("画 了 一个直角“); class Adapter : Graphicsprivate Angle angle = new Angle(); public override void DrawOanzle DrawAnzle 0 :class Programst a-t ic void. Main (st r

28、irtg args)Graphics circle = new Circle(): circle DrawO :Graphics rect = new Sect angle O : rcct Dr a-w O :Graphics line = new Line (): line Dm ():Graphics adapter = new Adapter(): adapt cr Draw O ;ConsoleRead():6运行结果实验六桥接模式的应用1实验目的1) 掌握桥接模式(Bridge )的特点2) 分析具体问题,使用桥接模式进行设计。2实验内容和要求个咖啡店可以提供大杯(JorumCof

29、fee) s中杯(MediumCoffec) s小杯 (SmallCoffee)的咖啡(Coffee),为了满足不同用户的口味,在咖啡中可以添加牛 奶(Milk),或者糖(Sugar),或者柠檬(Lemon),提供给用户不同口味的组合,如 大杯咖啡加牛奶,中杯咖啡加糖,小杯咖啡加柠檬,小杯咖啡加糖等。应用桥 接模式,用C#控制台应用程序实现该设计。绘制该模式的UML图。3模式结构图4 UML类图Condiment+ShoQ: voidSuger-ShowQ: voidLemon+SbowQ: void+Sbc*/0: voidcoffeecondiment; Condnientsmallcof

30、fee4ShowQ: vokJMediumCoHee+Sh%0; vdd4AddCordmentcondiTent: Condnient): void5代码/调味品类abstract class Con.diirient public abstract void Sho*w();class Suger : Condijnentpublic override void Show()C onsole. Vfr it eLine C 0 *'):class Milk : Condiment|public override void Sho*w()Console. Writ eLine C&#

31、39;牛奶"): class Lemon. : CondiiTLerrt public override void Show()Console Writ eLine ("柠 橡");1abstxact class CoffeeproteGted CondinGrrt condiment:public void AddCondiment (Condiment condiment) this condimerrt = condijnent:public abstract void ShowO :"小杯咖啡class SmaLLCoffee : Coffeep

32、ublic override void ShowOConso 1 e- Write ("小杯咖 U非添加 了"): condiment Show():"中杯咖啡class MediuniCoffee : Coffeepublic override void ShowOConso 1 e- Write ("中杯咖 U非添加 了"): condiment Show():犬杯咖啡class JorumCcffee ; Coffee public override void ShowOConsole. Write C大杯咖啡添加7"): co

33、ndiment ShowO :class Prcigrarristatic void Main (string args)Coffee coffee = new SmaLLCoffee();coffee. AddCondiment(new Sugex(); coffee. Show ();coffee. AddCondiment(new Mi lk (): coffee Show():coffeeAddCondiment(new Lemon(): coffee Show():Console ReadO :6运行结果 iil珂E:/4各种课程/设计蟆式/设卜巳i回糖牛柠777实验七装饰模式的应用

34、1实验目的1) 掌握装饰模式(Decorator )的特点2) 分析具体问题,使用装饰模式进行设计。2实验内容和要求“喜羊羊逃命”游戏:喜羊羊被灰太狼追,喜羊羊最多5条命,灰太狼每咬 到喜羊羊一次,喜羊羊就要少一条命。在逃的过程中喜羊羊可以吃到三种苹 果,吃“红苹果”可以给喜羊羊加上保护罩,吃“绿苹果”可以加快喜羊羊奔跑速 度,吃“黄苹果”可以使喜羊羊趟看水跑。应用装饰模式,用C#控制台应用程序 实现该设计。绘制该模式的UML图。提示:这个例子如果用类的继承来实现的话那可就麻烦了,你需要为喜羊 羊派生3*2*1=6个子类(有保护罩的喜羊羊,奔跑速度加快的喜羊羊,会趟水 的喜羊羊,既有保护罩又会

35、趟水的喜羊羊,奔跑速度快且会趟水的喜羊羊,有 保护罩且奔跑速度快的喜羊羊,有保护罩、奔跑速度快且会趟水的喜羊羊),如 果使用装饰模式的那就不用派生诸多子类了,当喜羊羊每吃到一个苹果,我们 就用装饰模式给喜羊羊加一个动态增加一个新功能即可。Conipo ncn t.ConcreteDecaratorA-AddStore+Oixrrat ion (3模式结构图ConcreteDecoratorBtOpcTeit i oji () -4-AddB<!hav ior ()4 UML类图5代码class PleasantGoatprivate string name:public Pleasant

36、G-oa-t () public PleasantG-oat (string njne)this.rtajne = name :public virtual void ShowOConsole. Writ eLine C 0 "najTie): class Apple ; PleasantGoatprotected PleasantGoat component:Ipublic void AddSkill(PleasantGoat component) this, component = component:public override void ShovOif (componeni

37、: 1= null)componen-t. Show();class RedApple : Applepublic override void ShowOConsole. Write ("有保护詈的“):base. ShoO :class GreenApple : Apple public override void Show() Console. VriteC"奔跑速度加快的“); base. ShowO :class YellowApple : Applepublic override void ShowOConsole.IVriteC会趟水的“); base Sho-

38、w ():static void Main(string: args)PleasntCoat goat = new PlesarrtGgt ("寿 羊羊");Cons ole. Writ eLine ("荻得技能的第一种情况;“); RedApple red.1 = nev RedAppleO ;GreenApple greenl = nev GreenAppleO :red.1. AddSkill (goat):greenl. AddSki11(redl): greenl. ShovO :Console. Writ eLine C 5获得技能的第二种情况;&qu

39、ot;:GreenApple green2 = nev GreenAppleO : YellovApple yellowZ = new YellovAppleO :green2.AddSki11(goat): yellow2 AddSkill (grc:en2): yellow2 ShowO :Console Read.0 :6运行结果 iileVE:/4各种课凰设计奠式/设计=I回实验八外观模式的应用1实验目的1)掌握外观模式(Facade )的特点2)分析具体问题,使用外观模式进行设计。2实验内容和要求个保安系统的,由录像机、电灯、红外线监控和警报器组成。保安系统 的操作人员需要经常将这些

40、仪器启动和关闭。保安类需要用到所有的录像机 (Camera).电灯(Light)、感应器(Sensor)和警报器(Alarm)对象,保安觉得使用不 方便。应用外观模式,用C#控制台应用程序改进该设计。绘制该模式的UML 图。3模式结构图4 UML类图5代码 abst ract class Deviceprotected, string: name;public Device () public Device(st ring name)this name = name:public abstract void TurnOn(): public abstxact void TurnOff();cl

41、ass Camera : Devicepublic CameraO : baseCajneraff)public override void TurnOn()Console. Wrri/t eLine ("打 开了 " + nante): public override void TurnOff()Conso 1 e. Writ eLine ("jij f “ + name):class Light : Device public Light () : baseC'Light)public override void TurnOn()Console Wr

42、i*teLing ("扌丁开"7 " + name); public override void TurnOff ()Console Wr i/teLing ("关 闭了 " + name); class Sensor : Devicepublie Sensor(): base("Sensor")publie override void TurnOn()Console聊rzi/teLine ("扌丁开 了 " + name); publie override void TurnOff ()IConsol&

43、amp; Writ eLine It 7 " 十 name);class Alarm : Device public AlarmO : baseC'Alarni)public override void TurnOn()Console Wri/tE匸ing ("打开了 " + name); public override void TurnOff ()Console Wri/tE匸ing ("关 闭了 " + name); class SecurityFacadeprivate st at i c SecurityFacade secu

44、rity; private IList<Device> devices;private SecurityFacade () public st at ic Securit yFacad & Get Inst arice ()if (null = securily)securi-ty = new Seciari + yFacade ():IList <Device> devices = new List<Device> ():Camera camera = new CanneraO : Light light = new Light (): Senso

45、r sensor = new Sensor O : Alarm alarm = new Alarm():devices. Add(camera):devi c es. Add(1i ght):devices. Add(sensor): devices. Add(alarm):securityDevices = devices:return security:public IList<Device> Devicesset devices = value: public void Activat e ()£orc=acli (var it cin in devices)it

46、em. TurnOn ():public void Deact ivate ()foreach (var it em in devices)it em. TurnOff ():1class Prograjnstatic void Main (string args)SecurityFacade security = SecurityFacade Get InistancE (): Console. Writ eLine C启动保安系纟克):security Act ivateO :Console. Writ eLine C关 ifM呆安系纟克v):s&curityDeactivat e

47、 ():Console Re:a.d ():6运行结果匍刨/但/4各种课程/设计摸式L)|回;启动保安系统打幵了 Camera打幵了 Light;打幵了 Ah"关闭保安系统:丁幵了 SensorCanepaSensoir去才了 A lam实验九观察者模式的应用1实验目的1) 掌握观察者模式(Observer )的特点2) 分析具体问题,使用观察者模式进行设计。2实验内容和要求网上商店中如果商品(product )在名称(name )、价格(price )等方面有 变化,系统能自动通知会员,将是网上商店区别传统商店的一大特色。如何设 计实现?说明你所选择的设计模式,画出类关系图并指明各

48、个类的角色。应用 观察者模式,用C#控制台应用程序改进该设计。绘制该模式的UML图。3模式结构图4 UML类图5代码class Productpublic const string CHANGED_NAME ="商品名称变动":public const string CHANGED_PRICE ="商品仔i格妾动": private string name;private float price:private IList<ProductObserver> observers = new List<ProductObserver>

49、():public Product()public Pxoduct (string namcjifloat price)| this, name = nme;this.price = price;public string: GetNameOreturn name :public void SetName(st r ing name) this nanLe = name;-this Not ify (CHANGEDJNAME):public float GetPriceC)return price:public void SetPrice(float price) this.price = p

50、rice;t hi s. Not if y (CHAI-IGED.PRICE):public void Ad.d.O'bsetrv&r (Product Ob server observ&r) observers Add(observer):public void De lei: eObserver (Pro duct Observer observer)observers. Reinove (observer);public void Notiy(stiring type)foreach (ProductObserver observer in. observers)

51、observer .Update Cthis, type):abstrac七 class Produc七0bserverabstract public void Update(Product product5 string type):class Pro duct N ajneOb server ; ProductObserverpublic override: void Update (Product product, string type)if (type = Pro duct. CHANGE J NAME)Console. "Writ eLine C 商品的名称变为:&quo

52、t;+pr o duct. Get Name ():class ProductPriceObserver : Productobserverpublic override void Updat e(Product product st ring type)if (type = Product.CHANGED.PRICE)Cons ole. "Writ eLine ("商品的价格变为:"+ product. GetPrice (); 1class PrograjRstatic void Main (st ring args)Product product = new

53、 Product ("可 口可乐4. 5£):ProductObserver observer 1 = new ProductNameObserver(); ProductObserver observer2 = new ProductPriceObserver(); product. AddObs e rver(ob server1);product. AddObs e rver(ob serverS);Conso 1 e. V/riteLine C'*改动前J :Conso 1 e. WriteLine ("商品名称:,Y+product. GetNameO): Console. Writ eLine C

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论