创建型 5
-----------------------------------------------------------------------------------------
1. Builder ------- 分离整体构建算法和部件构造
具体问题:数据导出格式(头,体,尾)
一般问题:同一个构建过程有着不同的表示
客户端:
2. Prototype ------- 克隆生成对象
具体问题:订单处理系统
一般问题:一个系统想要独立于它想要使用的对象
客户端:
Prototype newPrototype = prototype.clone();
3. Singleton -------- 控制实例数目
具体问题:读取配置文件的内容
----------------------------------------------------------------------------------------------------------------------
4. 简单工厂 -------- 选择实现
-----------------------------------------------------------------------------------------
5. Factory Method -------- 延迟到子类选择实现
6. Abstract Factory -------- 选择产品簇的实现
----------------------------------------------------------------------------------------
结构型 7
-----------------------------------------------------------------------------------------
1.Decorator ------- 动态组合
具体问题:复杂的奖金计算
一般问题:不影响其他对象的情况下,以动态,透明的方式给对象添加职责;
public abstract class Component
{
public abstract double calcPrice(string user, DateTime begin, DateTime end);
}
public class ConcreteComponent : Component
{
public override double calcPrice(string user, DateTime begin, DateTime end)
{
return 0;
}
}
public abstract class Decorator : Component
{
protected Component _c;
public Decorator(Component c)
{
this._c = c;
}
public override double calcPrice(string user, DateTime begin, DateTime end)
{
return this._c.calcPrice(user, begin, end);
}
}
public class MonthPrizeDecorator : Decorator
{
public MonthPrizeDecorator(Component c) : base(c) { }
public override double calcPrice(string user, DateTime begin, DateTime end)
{
double money = base.calcPrice(user, begin, end);
return money + 100;
}
}
public class SumPrizeDecorator : Decorator
{
public SumPrizeDecorator(Component c) : base(c) { }
public override double calcPrice(string user, DateTime begin, DateTime end)
{
double money = base.calcPrice(user, begin, end);
return money + 1000;
}
}
public class GroupPrizeDecorator : Decorator
{
public GroupPrizeDecorator(Component c) : base(c) { }
public override double calcPrice(string user, DateTime begin, DateTime end)
{
double money = base.calcPrice(user, begin, end);
return money + 10000;
}
}
客户端:
Component c1 = new ConcreteComponent();
Decorator d1 = new MonthPrizeDecorator(c1);
d1.calcPrice("aa", DateTime.Now, DateTime.Now);
Decorator d2 = new SumPrizeDecorator(d1);
d2.calcPrice("bb", DateTime.Now, DateTime.Now);
Decorator d3 = new GroupPrizeDecorator(d2);
d3.calcPrice("cc", DateTime.Now, DateTime.Now);
2.Composite ------- 统一叶子对象和组合对象
具体问题:商品类别树;
一般问题:部分整体层次结构;统一地使用组合结构中的所有对象;
客户端:
Component root = new Composite(“服装”);
Component c1 = new Composite(“男装”);
Component c2 = new Composite(“女装”);
Component leaf1 = new Leaf(“衬衣”);
Component leaf2 = new Leaf(“夹克”);
Component leaf3 = new Leaf(“裙子”);
Component leaf4 = new Leaf(“套装”);
root.addChild(c1);
root.addChild(c2);
c1. addChild(leaf1);
c1. addChild(leaf2);
c2. addChild(leaf3);
c2. addChild(leaf4);
3.Adapter ------- 转换匹配,复用功能
具体问题:同时支持数据库和文件的日志管理
一般问题:转换接口;复用类;
客户端:
Adaptee adaptee = new Adaptee ();
Target target = new Adapter(adaptee);
target.request();
4.Facade ------- 封装交互简化调用
具体问题:代码生成三层模块
一般问题:复杂的子系统提供一个简单的接口;客户程序和抽象类的实现部分松散耦合;
构建多层结构的系统;
Class Façade
{
Public void test()
{
AModultApi a = new AModuleImpl();
a.testA();
BModultApi b = new BModuleImpl();
b.testB();
}
}
客户端:
new Façade().test();
5.Flyweight ------- 分离与共享
具体问题:权限中读取缓存中的数据
一般问题:如果一个应用程序使用了大量的细粒度对象
6.Proxy ------- 控制对象访问
具体问题:读取大量数据问题
一般问题 :(1)虚代理:需要创建开销很大的对象; (2)保护代理:控制对原始对象的访问,判断权限;(3)远程代理:为一个对象在不同的地址空间提供局部代表;(4)智引代理:在访问对象执行一些附加操作;
7.Bridge ------- 分离抽象和实现
具体问题:发送消息(内部,邮件,手机)(普通,加急,特急)
一般问题:抽象部分和实现部分能够扩展;采用继承的方案,产生很多类;
public interface MessageImplementor
{
void send(string message, string toUser);
}
public interface AbstractMessage
{
void sendMessage(string message, string toUser);
}
public class MessageSMS : MessageImplementor
{
public void send(string message, string toUser)
{
Console.WriteLine("站内短消息发送" + message + toUser);
}
}
public class MessageEmail : MessageImplementor
{
public void send(string message, string toUser)
{
Console.WriteLine("e-mail发送" + message + toUser);
}
}
public class CommonMessage : AbstractMessage
{
private MessageImplementor _impl;
public CommonMessage(MessageImplementor impl)
{
this._impl = impl;
}
public void sendMessage(string message, string toUser)
{
this._impl.send(message, toUser);
}
}
public class UrgencyMessage : AbstractMessage
{
private MessageImplementor _impl;
public UrgencyMessage(MessageImplementor impl)
{
this._impl = impl;
}
public void sendMessage(string message, string toUser)
{
this._impl.send(message, toUser);
}
}
客户端:
MessageImplementor impl = new MessageSMS();
AbstractMessage m = new CommonMessage(impl);
m.sendMessage("aa","bb");
impl = new MessageEmail();
m = new CommonMessage(impl);
m.sendMessage("cc","dd");
行为型 11
1. Strategy ------- 分离算法,选择实现
具体问题:向客户包报价
一般问题:封装算法;同一个算法,不同实现;if /else语句
客户端:
Strategy strategy = new ConcreteStrategyA();
Context context = new Context(strategy);
context.contextInterface();
2. State ------- 根据状态来分离和选择行为
具体问题:在线分类投票
一般问题:一个对象的行为取决于状态;依赖于状态的多分支结构;
3. Command ------- 封装请求
具体问题:开机模式
一般问题:不同的时刻指定,排列,执行请求; undo;
客户端:
Receicer receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoker invoker = new Invoker();
invoker.setCommand(command);
invoker.runCommand();
4. Observer ------- 触发联动
具体问题:订阅报纸;
一般问题:操作依赖于状态的变化;更改一个对象,连同更改其他对象;
客户端:
ConcreteSubject subject = new ConcreteSubject ();
ConcreteObserver a1 = new ConcreteObserver ();
a1.setName(“张三”);
ConcreteObserver a2= new ConcreteObserver ();
a2.setName(“李四”);
ConcreteObserver a3 = new ConcreteObserver ();
a3.setName(“王五”);
subject.attach(a1);
subject.attach(a2);
subject.attach(a3);
subject.setContent();
5. Mediator -------- 封装交互
具体问题:主板上各个配件交互
一般问题:一组对象之间的通信;
客户端:
ConcreteMediator mediator = new ConcreteMediator();
ConcreteColleagueA a = new ConcreteColleagueA (mediator) ;
mediator..setConcreteColleagueA(a);
a.someOperation();
6. Chain of Responsibility-------- 分离职责 ,动态组合
具体问题:申请聚餐费用项目经理——》部门经理——》总经理
一般问题:如果多个对象可以处理同一个请求,具体哪个对象处理请求,是运行动态确定
public abstract class Handler
{
protected Handler _successor = null;
public void setSuccessor(Handler successor)
{
this._successor = successor;
}
public abstract string handleFeeRequest(string user, double fee);
}
public class ProjectManager : Handler
{
public override string handleFeeRequest(string user, double fee)
{
string str = string.Empty;
if (fee < 500)
{
str = "项目经理处理!";
}
else
{
if (this._successor != null)
{
return _successor.handleFeeRequest(user, fee);
}
}
return str;
}
}
public class DepManager : Handler
{
public override string handleFeeRequest(string user, double fee)
{
string str = string.Empty;
if (fee < 1000)
{
str = "部门经理处理!";
}
else
{
if (this._successor != null)
{
return _successor.handleFeeRequest(user, fee);
}
}
return str;
}
}
public class GeneralManager : Handler
{
public override string handleFeeRequest(string user, double fee)
{
string str = string.Empty;
if (fee >= 1000)
{
str = "总经理处理!";
}
else
{
if (this._successor != null)
{
return _successor.handleFeeRequest(user, fee);
}
}
return str;
}
}
客户端:
Handler h1 = new GeneralManager();
Handler h2 = new DepManager();
Handler h3 = new ProjectManager();
h3.setSuccessor(h2);
h2.setSuccessor(h1);
Console.WriteLine(h3.handleFeeRequest("aa", 400));
Console.WriteLine(h3.handleFeeRequest("aa", 600));
Console.WriteLine(h3.handleFeeRequest("aa", 1400));
输出:
项目经理处理!
部门经理处理!
总经理处理!
7. Visitor ----- 预留回路,回调实现
具体问题:客户管理增加偏好分析和价值分析
一般问题:给对象结构中的元素对象定义新的操作;
模式使用前:
public abstract class Customer
{
public string customerId { get; set; }
public string name { get; set; }
public abstract void serviceRequest();
public abstract void predilectionAnalyze();
public abstract void worthAnalyze();
}
public class EnterpriseCustomer : Customer
{
public string linkman { get; set; }
public string linkTelephone { get; set; }
public string registerAddress { get; set; }
public override void serviceRequest()
{
Console.WriteLine(this.name + "企业提出服务请求!");
}
public override void predilectionAnalyze()
{
Console.WriteLine(this.name + "企业偏好分析!");
}
public override void worthAnalyze()
{
Console.WriteLine(this.name + "企业价值分析!");
}
}
public class PersonalCustomer : Customer
{
public string telephone { set; get; }
public int age { set; get; }
public string registerAddress { get; set; }
public override void serviceRequest()
{
Console.WriteLine(this.name + "客户提出服务请求!");
}
public override void predilectionAnalyze()
{
Console.WriteLine(this.name + "各户偏好分析!");
}
public override void worthAnalyze()
{
Console.WriteLine(this.name + "各户价值分析!");
}
}
static void Main()
{
List<Customer> cols = testData();
foreach(Customer col in cols)
{
col.predilectionAnalyze();
col.worthAnalyze();
}
}
static List<Customer> testData()
{
List<Customer> col = new List<Customer>();
Customer cm1 = new EnterpriseCustomer();
cm1.name = "a";
col.Add(cm1);
Customer cm2 = new EnterpriseCustomer();
cm2.name = "b";
col.Add(cm2);
Customer cm3 = new PersonalCustomer();
cm3.name = "b";
col.Add(cm3);
return col;
}
输出:
a企业偏好分析!
a企业价值分析!
b企业偏好分析!
b企业价值分析!
b各户偏好分析!
b各户价值分析!
模式使用后:
public abstract class Customer
{
public string customerId { get; set; }
public string name { get; set; }
public abstract void accept(Visitor visitor);
//public abstract void serviceRequest();
//public abstract void predilectionAnalyze();
//public abstract void worthAnalyze();
}
public class EnterpriseCustomer : Customer
{
public string linkman { get; set; }
public string linkTelephone { get; set; }
public string registerAddress { get; set; }
//public override void serviceRequest()
//{
// Console.WriteLine(this.name + "企业提出服务请求!");
//}
//public override void predilectionAnalyze()
//{
// Console.WriteLine(this.name + "企业偏好分析!");
//}
//public override void worthAnalyze()
//{
// Console.WriteLine(this.name + "企业价值分析!");
//}
public override void accept(Visitor visitor)
{
visitor.visitEnteroriseCustomer(this);
}
}
public class PersonalCustomer : Customer
{
public string telephone { set; get; }
public int age { set; get; }
public string registerAddress { get; set; }
//public override void serviceRequest()
//{
// Console.WriteLine(this.name + "客户提出服务请求!");
//}
//public override void predilectionAnalyze()
//{
// Console.WriteLine(this.name + "各户偏好分析!");
//}
//public override void worthAnalyze()
//{
// Console.WriteLine(this.name + "各户价值分析!");
//}
public override void accept(Visitor visitor)
{
visitor.visitPersonalCustomer(this);
}
}
public interface Visitor
{
void visitEnteroriseCustomer(EnterpriseCustomer ec);
void visitPersonalCustomer(PersonalCustomer pc);
}
public class ServiceRequestVisitor : Visitor
{
public void visitEnteroriseCustomer(EnterpriseCustomer ec)
{
Console.WriteLine(ec.name + "企业提出服务请求!");
}
public void visitPersonalCustomer(PersonalCustomer pc)
{
Console.WriteLine(pc.name + "客户提出服务请求!");
}
}
public class PredilectionAnalyzwVisitor : Visitor
{
public void visitEnteroriseCustomer(EnterpriseCustomer ec)
{
Console.WriteLine(ec.name + "企业偏好分析!");
}
public void visitPersonalCustomer(PersonalCustomer pc)
{
Console.WriteLine(pc.name + "各户偏好分析!");
}
}
public class WorthAnalyzwVisitor : Visitor
{
public void visitEnteroriseCustomer(EnterpriseCustomer ec)
{
Console.WriteLine(ec.name + "企业价值分析!");
}
public void visitPersonalCustomer(PersonalCustomer pc)
{
Console.WriteLine(pc.name + "各户价值分析!");
}
}
public class ObjectStructure
{
private List<Customer> col = new List<Customer>();
public void handleRequest(Visitor visitor)
{
foreach(Customer cm in col)
{
cm.accept(visitor);
}
}
public void addElement(Customer el)
{
this.col.Add(el);
}
}
ObjectStructure os = new ObjectStructure();
Customer cm1 = new EnterpriseCustomer();
cm1.name = "a";
os.addElement(cm1);
Customer cm2 = new EnterpriseCustomer();
cm2.name = "b";
os.addElement(cm2);
Customer cm3 = new PersonalCustomer();
cm3.name = "b";
os.addElement(cm3);
ServiceRequestVisitor srVisitor = new ServiceRequestVisitor();
os.handleRequest(srVisitor);
PredilectionAnalyzwVisitor paVisitor = new PredilectionAnalyzwVisitor();
os.handleRequest(paVisitor);
WorthAnalyzwVisitor waVisitor = new WorthAnalyzwVisitor();
os.handleRequest(waVisitor);
输出:
a企业提出服务请求!
b企业提出服务请求!
b客户提出服务请求!
a企业偏好分析!
b企业偏好分析!
b各户偏好分析!
a企业价值分析!
b企业价值分析!
b各户价值分析!
8. Interpreter ----- 分离实现,解释执行
具体问题:读取配置文件
一般问题:当一个语言需要解释执行,语言中的句子表示为一个抽象语法树
9. Memento -------- 保护和恢复内部状态
具体问题:开发访真系统
一般问题:保存一个对象在某一个时刻的全部或者部分状态;
客户端:
Originator ori = new Originator(“test”);
ori.runPhaseOne();
Caretaker care = new Caretaker ();
Memento memento = ori.createMemento();
care saveMemento(memento);
ori. schemal1();
ori.setMemento(care.retireMemento());
ori.schemal2();
10. Template Method -------- 固定算法骨架
11. Iterator -------- 控制访问聚合对象中的元素
具体问题:访问List /数组的数据
一般问题:访问聚合对象
----------------------------------------------------------------------------------------------------------------------