搜索
您的当前位置:首页正文

实验一代码

来源:二三娱乐
实验一:工厂模式的应用

实验目的

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

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

实验内容和要求

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

实验UML图

实验源代码

using System;

using System.Collections.Generic; using System.Linq; using System.Text;

namespace Factory {

interface ComputerFactory {

Computer CreateComputer(); }

abstract class Computer {

protected string computer;

public abstract string newcomputer(); }

class Hp : Computer {

public override string newcomputer() {

return \"This a new Hp computer\"; } }

class Dell : Computer {

public override string newcomputer() {

return \"This a new Dell computer\"; } }

class Lenovo : Computer {

public override string newcomputer() {

return \"This a new Lenovo computer\"; } }

class Acer : Computer {

public override string newcomputer() {

return \"This a new Acer computer\"; } }

class HpFactory : ComputerFactory {

public Computer CreateComputer() {

return new Hp(); } }

class DellFactory : ComputerFactory {

public Computer CreateComputer() {

return new Dell(); } }

class LenovoFactory : ComputerFactory {

public Computer CreateComputer() {

return new Lenovo(); } }

class AcerFactory : ComputerFactory {

public Computer CreateComputer() {

return new Acer();

} }

class Program {

static void Main(string[] args) {

ComputerFactory HpComputer = new HpFactory(); ComputerFactory DellComputer = new DellFactory(); ComputerFactory LenovoComputer = new LenovoFactory(); ComputerFactory AcerComputer = new AcerFactory(); Computer Hp = HpComputer.CreateComputer(); Computer Dell = DellComputer.CreateComputer(); Computer Lenovo = LenovoComputer.CreateComputer(); Computer Acer = AcerComputer.CreateComputer();

Console.WriteLine(\"They are new computers:\"); string result1 = Hp.newcomputer(); string result2 = Dell.newcomputer(); string result3 = Lenovo.newcomputer(); string result4= Acer.newcomputer(); Console.WriteLine( result1); Console.WriteLine( result2); Console.WriteLine( result3); Console.WriteLine( result4);

Console.ReadLine();

} } }

实验结果截屏

实验小结

通过本次实验,加深了对工厂模式的理解:在工厂方法模式中,父类负责定义创建对象的公共接口,而子类则负责生成具体的对象,这样做的目的是将类的实例化操作延迟到子类中完成,即由子类来决定究竟应该实例化(创建) 哪一个类。

因篇幅问题不能全部显示,请点此查看更多更全内容

Top