设计模式实验报告

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验一单例模式的应用

1 实验目的

1) 掌握单例模式(Singleton)的特点

2) 分析具体问题,使用单例模式进行设计。

2 实验内容和要求

很多应用项目都有配置文件,这些配置文件里面定义一些应用需要的参数数据。

通常客户端使用这个类是通过new一个AppConfig的实例来得到一个操作配置文件内容的对象。如果在系统运行中,有很多地方都需要使用配置文件的内容,系统中会同时存在多份配置文件的内容,这会严重浪费内存资源。

事实上,对于AppConfig类,在运行期间,只需要一个对象实例就够了。那么应该怎么实现呢用C#控制台应用程序实现该单例模式。绘制该模式的UML图。

3 实验代码

using System;

using ;

using ;

using AppConfig

{

public class Singleton

{

private static Singleton instance;

private Singleton()

{

}

public static Singleton GetInstance()

{

if (instance == null)

{

instance = new Singleton();

}

return instance;

}

}

class Program

{

static void Main(string[] args)

{

Singleton singletonOne = ();

Singleton singletonTwo = ();

if (singletonTwo))

{

("singletonOne 和 singletonTwo 代表的是同一个实例"); }

else

{

("singletonOne 和 singletonTwo 代表的是不同实例"); }

();

}

}

}

4 实验结果

实验二工厂模式的应用

1 实验目的

1) 掌握工厂模式(Factory)的特点

2) 分析具体问题,使用工厂模式进行设计。

2 实验内容和要求

有一个OEM制造商代理做HP笔记本电脑(Laptop),后来该制造商得到了更多的品牌笔记本电脑的订单Acer,Lenovo,Dell,该OEM商发现,如果一次同时做很多个牌子的本本,有些不利于管理。利用工厂模式改善设计,用C#控制台应用程序实现该OEM制造商的工厂模式。绘制该模式的UML图。

3 实验代码

using System;

using ;

using ;

using Factory

{

class Computer

{

public virtual void print()

{

("我是Computer\n");

}

}

class HPComputer:Computer

{

public override void print()

{

("我是HPComputer\n");

}

}

class AcerComputer : Computer

{

public override void print()

{

("我是AcerComputer\n");

}

}

class DellComputer : Computer

{

public override void print()

{

("我是DellComputer\n");

}

}

interface Ifactory

{

Computer CreateComputer();

}

class HPFactory : Ifactory

{

public Computer CreateComputer()

{

return new HPComputer();

}

}

class AcerFactory : Ifactory

{

public Computer CreateComputer()

{

return new AcerComputer();

}

}

class DellFactory : Ifactory

{

public Computer CreateComputer()

{

return new DellComputer();

}

}

class Program

{

static void Main(string[] args)

{

Ifactory factory = new HPFactory();

Computer computer = ();

();

factory = new DellFactory();

computer = ();

();

factory = new AcerFactory();

相关文档
最新文档