专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。简单工厂模式又称为静态工厂方法模式,属于类的创建型模式,通常它根据自变量的不同返回不同的类的实例。
示例:电子付款系统
using System;
namespace EFT
{
//抽象电子付款类
abstract class EFT
{
public abstract void process();
}
//具体子类,虚拟检查
class VirtualCheck:EFT
{
public override void process()
{
Console.WriteLine("虚拟支票处理中");
}
}
//具体子类,万事达卡
class MasterCard:EFT
{
public override void process()
{
Console.WriteLine("万事达卡处理中");
}
}
//简单工厂类
class EFTFactory
{
public EFT createEFT(string type)
{
switch (type.ToLower())
{
case "virtualcheck":
return new VirtualCheck();
case "mastercard":
return new MasterCard();
default:
return null;
}
}
}
//客户应用测试
class Client
{
[STAThread]
static void Main(string[] args)
{
EFT eft;
EFTFactory eftFactory = new EFTFactory();
eft = eftFactory.createEFT("VirtualCheck");
eft.process();
eft = eftFactory.createEFT("mastercard");
eft.process();
Console.ReadLine();
}
}
}
示例:学校登录系统
using System;
namespace SchoolSystem
{
//Base Class 基类
public class SchoolUser
{
public string FName;
public string LName;
public string UserType;
public void Show()
{
Console.WriteLine("First Name: " + FName + "\n");
Console.WriteLine("Last Name: " + LName + "\n");
Console.WriteLine("User Type: " + UserType + "\n");
}
}
//Derived Classes 派生类,校负责人
public class SchoolPrincipal : SchoolUser
{
public SchoolPrincipal()
{
FName = "David";
LName = "Smith";
UserType = "Principal";
}
}
//派生类,校教师
public class SchoolTeacher : SchoolUser
{
public SchoolTeacher()
{
FName = "Patrecia";
LName = "Terry";
UserType = "Teacher";
}
}
//简单工厂类
public class SimpleFactory
{
public SchoolUser GetSchoolUser(string user, string password)
{
if (user == "Principal" && password == "Principal")
return new SchoolPrincipal();
if (user == "Teacher" && password == "Teacher")
return new SchoolTeacher();
return null;
}
}
//客户应用
class Client
{
[STAThread]
static void Main(string[] args)
{
SimpleFactory sf = new SimpleFactory();
SchoolUser su;
su = sf.GetSchoolUser("Principal","Principal");
Console.WriteLine("-------------------校长登录--------------------\n");
su.Show();
Console.WriteLine("-------------------教师登录--------------------\n");
su = sf.GetSchoolUser("Teacher","Teacher");
su.Show();
Console.ReadLine();
}
}
}
posted on 2008-10-06 13:49
zhanghaibin 阅读(334)
评论(0) 编辑 收藏 引用 所属分类:
学习笔记