1.adapter适配器
可分为类适配器,对象适配器。在类设计之后
类适配器:
// 已存在的、具有特殊功能、但不符合我们既有的标准接口的类
class Adaptee {
public void specificRequest() {
System.out.println("被适配类具有 特殊功能...");
}
}
// 目标接口,或称为标准接口
interface Target {
public void request();
}
// 具体目标类,只提供普通功能
class ConcreteTarget implements Target {
public void request() {
System.out.println("普通类 具有 普通功能...");
}
}
// 适配器类,继承了被适配类,同时实现标准接口
class Adapter extends Adaptee implements Target{
public void request() {
super.specificRequest();
}
}
// 测试类
public class Client {
public static void main(String[] args) {
// 使用普通功能类
Target concreteTarget = new ConcreteTarget();
concreteTarget.request();
// 使用特殊功能类,即适配类
Target adapter = new Adapter();
adapter.request();
}
}
对象适配器:
// 适配器类,直接关联被适配类,同时实现标准接口
class Adapter implements Target{
// 直接关联被适配类
private Adaptee adaptee;
// 可以通过构造函数传入具体需要适配的被适配类对象
public Adapter (Adaptee adaptee) {
this.adaptee = adaptee;
}
public void request() {
// 这里是使用委托的方式完成特殊功能
this.adaptee.specificRequest();
}
}
// 测试类
public class Client {
public static void main(String[] args) {
// 使用普通功能类
Target concreteTarget = new ConcreteTarget();
concreteTarget.request();
// 使用特殊功能类,即适配类,
// 需要先创建一个被适配类的对象作为参数
Target adapter = new Adapter(new Adaptee());
adapter.request();
}
}
2.bridge桥接器
抽象部分和实现部分分离,在类设计之前
namespace CarRunOnRoad_Bridge_
2{
3
4 //抽象路
5 public abstract class AbstractRoad
6 {
7 protected AbstractCar car;
8 public AbstractCar Car
9 {
10 set
11 {
12 car = value;
13 }
14 }
15
16 public abstract void Run();
17 }
18
19 //高速公路
20 public class SpeedWay : AbstractRoad
21 {
22 public override void Run()
23 {
24 car.Run();
25 Console.WriteLine("高速公路上行驶");
26 }
27 }
28
29 //市区街道
30 public class Street : AbstractRoad
31 {
32 public override void Run()
33 {
34 car.Run();
35 Console.WriteLine("市区街道上行驶");
36 }
37 }
38}
1namespace CarRunOnRoad_Bridge_
2{
3 //抽象汽车
4 public abstract class AbstractCar
5 {
6 public abstract void Run();
7 }
8
9 //小汽车;
10 public class Car : AbstractCar
11 {
12 public override void Run()
13 {
14 Console.Write("小汽车在");
15 }
16 }
17
18 //公共汽车
19 public class Bus : AbstractCar
20 {
21 public override void Run()
22 {
23 Console.Write("公共汽车在");
24 }
25 }
26}
static void Main(string[] args)
2 {
3 //小汽车在高速公路上行驶;
4 AbstractRoad Road1 = new SpeedWay();
5 Road1.Car = new Car();
6 Road1.Run();
7 Console.WriteLine("=========================");
8
9 //公共汽车在高速公路上行驶;
10 AbstractRoad Road2 = new SpeedWay();
11 Road2.Car = new Bus();
12 Road2.Run();
13
14
15
16 Console.Read();
17 }
3.composite组合
考虑树形结构,叶子节点和非叶子节点的一致性
透明模式处理:封装好,违背单一职责
/// <summary> /// The Component acts as abstract class. /// </summary> public abstract class Component { protected string name; public Component() { } public Component(string name) { this.name = name; } #region Methods public abstract Component Add(Component obj); public abstract void Remove(Component obj); public abstract void Display(int depth); #endregion }
/// <summary> /// The Composite acts as branch. /// </summary> public class Composite : Component { private IList<Component> _childen = new List<Component>(); public Composite() { } public Composite(string name) : base(name) { } /// <summary> /// Adds the branch or leaf obj. /// </summary> /// <param name="obj">The obj.</param> /// <returns></returns> public override Component Add(Component obj) { this._childen.Add(obj); return obj; } /// <summary> /// Removes the branch or leaf obj. /// </summary> /// <param name="obj">The obj.</param> public override void Remove(Component obj) { this._childen.Remove(obj); } /// <summary> /// Displays the tree's depth. /// </summary> /// <param name="depth">The depth.</param> public override void Display(int depth) { StringBuilder depthBuilder = new StringBuilder(new String('-', depth) + name); Console.WriteLine(depthBuilder); foreach (Component child in _childen) { child.Display(depth + 1); } } }
/// <summary> /// The "Leaf" acts as Leaf. /// </summary> public class Leaf : Component { public Leaf(string name) : base(name) { } public Leaf() { } /// <summary> /// Adds the branch or leaf obj. /// </summary> /// <param name="obj">The obj.</param> /// <returns></returns> public override Component Add(Component obj) { throw new NotSupportedException(); } /// <summary> /// Removes the branch or leaf obj. /// </summary> /// <param name="obj">The obj.</param> public override void Remove(Component obj) { throw new NotSupportedException(); } /// <summary> /// Displays the tree's depth. /// </summary> /// <param name="depth">The depth.</param> public override void Display(int depth) { StringBuilder depthBuilder = new StringBuilder(new String('-', depth) + name); Console.WriteLine(depthBuilder); } }
public class Program { static void Main(string[] args) { Client client = new Client(); Component component = client.Get("root"); Component componentA = component.Add(new Composite("BranchA")); componentA.Add(new Leaf("LeafA")); componentA.Add(new Leaf("LeafB")); Component componentB = component.Add(new Composite("BranchB")); component.Display(1); Console.ReadKey(); } }安全模式的:单一职责原则,但封装性差
/// <summary> /// The "DrawingProgramming" class acts as component. /// </summary> public abstract class DrawingProgramming { protected string _name; public abstract void Draw(); public DrawingProgramming(string name) { this._name = name; } }
/// <summary> /// The "Shape" class acts as composite. /// </summary> public class Shape : DrawingProgramming { IList<DrawingProgramming> _children = new List<DrawingProgramming>(); public Shape(string name) : base(name) { } #region DrawingProgramming 成员 public override void Draw() { StringBuilder depthBuilder = new StringBuilder(_name); Console.WriteLine(depthBuilder); foreach (DrawingProgramming child in _children) { child.Draw(); } } #endregion #region Methods public void Add(DrawingProgramming dp) { _children.Add(dp); } public void Remove(DrawingProgramming dp) { _children.Remove(dp); } #endregion }
/// <summary> /// The "Triangle" class acts as leaf. /// </summary> public class Triangle : DrawingProgramming { public Triangle(string name) : base(name) { } #region DrawingProgramming 成员 public override void Draw() { StringBuilder depthBuilder = new StringBuilder(_name); Console.WriteLine(depthBuilder); } #endregion } /// <summary> /// The "Circle" class acts as leaf. /// </summary> public class Circle : DrawingProgramming { public Circle(string name) : base(name) { } #region DrawingProgramming 成员 public override void Draw() { StringBuilder depthBuilder = new StringBuilder(_name); Console.WriteLine(depthBuilder); } #endregion }
4.decorator装饰器
为一个对象添加功能,不对整个类添加
/*----------------------------------------------------------------*/
/* class VisualComponent */
/*----------------------------------------------------------------*/
class VisualComponent
{
public:
VisualComponent(){}
virtual void Draw() = 0;
};
/*----------------------------------------------------------------*/
/* class TextView */
/*----------------------------------------------------------------*/
class TextViewControl : public VisualComponent
{
#define CONTENT_LEN 100
public:
TextViewControl(char* str, int len)
{
memset(m_content,0,CONTENT_LEN);
memcpy(m_content,str,len);
}
virtual void Draw()
{
cout<<" TextViewControl Draw content = "<<m_content<<endl;
}
private:
char m_content[CONTENT_LEN];
};
/*----------------------------------------------------------------*/
/* class Decorator */
/*----------------------------------------------------------------*/
class Decorator: public VisualComponent
{
public:
Decorator(VisualComponent* component)
{
m_componnet = component;
}
virtual void Draw()
{
m_componnet->Draw();
cout<<" I am Decorator Draw"<<endl;
}
private:
VisualComponent* m_componnet;
};
/*----------------------------------------------------------------*/
/* class BoarderDecorator */
/*----------------------------------------------------------------*/
class BoarderDecorator: public Decorator
{
public:
BoarderDecorator(VisualComponent* component, int boarderWidth):Decorator(component)
{
m_boarderWidth = boarderWidth;
}
virtual void Draw()
{
Decorator::Draw();
cout<<" I am BoarderDecorator Draw"<<endl;
this->DrawBorder();
}
protected:
void DrawBorder()
{
cout<<" DrawBorder m_boarderWidth = "<<m_boarderWidth<<endl;
}
private:
int m_boarderWidth;
};
/*----------------------------------------------------------------*/
/* class ScrollDecorator */
/*----------------------------------------------------------------*/
class ScrollDecorator: public Decorator
{
public:
ScrollDecorator(VisualComponent* component, int scrollHeight):Decorator(component)
{
m_scrollHeight = scrollHeight;
}
virtual void Draw()
{
Decorator::Draw();
cout<<" I am ScrollDecorator "<<endl;
this->DrawScroll();
}
protected:
void DrawScroll()
{
cout<<" DrawScroll m_scrollHeight = "<<m_scrollHeight<<endl;
}
private:
int m_scrollHeight;
};
int main()
{
char str[] = "TextViewControl";
TextViewControl* textView = new TextViewControl(str,strlen(str));
ScrollDecorator* scroll = new ScrollDecorator(textView,100);
BoarderDecorator* board = new BoarderDecorator(scroll,200);
board->Draw();
return 0;
}
5.facade外观
统一对外接口,一般配合单例
/*----------------------------------------------------------------*/
/* class Base */
/*----------------------------------------------------------------*/
class Base
{
public:
Base(){};
};
/*----------------------------------------------------------------*/
/* class SmsUtil */
/*----------------------------------------------------------------*/
class SmsUtil: public Base
{
#define SMS_CONTENT "I am sms content"
public:
SmsUtil(){}
bool checkReady()
{
cout<<"SmsUtil checkReady"<<endl;
return true;
}
bool getSmsContent(int msg_id,char* pContent)
{
cout<<"SmsUtil getSmsContent"<<endl;
strcpy(pContent,SMS_CONTENT);
return true;
}
};
/*----------------------------------------------------------------*/
/* class MmsUtil */
/*----------------------------------------------------------------*/
class MmsUtil: public Base
{
#define MMS_CONTENT "I am mms content"
public:
MmsUtil(){}
bool checkReady()
{
cout<<"MmsUtil checkReady"<<endl;
return true;
}
bool getMmsContent(int msg_id,char* pContent)
{
cout<<"MmsUtil getMmsContent"<<endl;
strcpy(pContent,MMS_CONTENT);
return true;
}
};
/*----------------------------------------------------------------*/
/* class PushUtil */
/*----------------------------------------------------------------*/
class PushUtil: public Base
{
#define PUSH_CONTENT "I am push content"
public:
PushUtil(){}
bool checkReady()
{
cout<<"PushUtil checkReady"<<endl;
return true;
}
bool getPushContent(int msg_id,char* pContent)
{
cout<<"PushUtil getPushContent"<<endl;
strcpy(pContent,PUSH_CONTENT);
return true;
}
};
/*----------------------------------------------------------------*/
/* class MsgFacade */
/*----------------------------------------------------------------*/
enum MsgType
{
SMS,
MMS,
PUSH,
MSG_ALL
};
class MsgFacade: public Base
{
protected:
MsgFacade()
{
m_sms = new SmsUtil();
m_mms = new MmsUtil();
m_push = new PushUtil();
}
public:
static MsgFacade* getInstance()
{
if (s_instance == NULL)
{
s_instance = new MsgFacade();
}
return s_instance;
}
static void closeInstance()
{
delete s_instance;
}
public:
bool checkReady(int type)
{
bool resutl = false;
resutl = m_sms->checkReady();
resutl &= m_mms->checkReady();
resutl &= m_push->checkReady();
return resutl;
}
bool getMsgContent(int type,int msg_id,char* pContent)
{
switch(type)
{
case SMS:
{
m_sms->getSmsContent(msg_id,pContent);
break;
}
case MMS:
{
m_mms->getMmsContent(msg_id,pContent);
break;
}
case PUSH:
{
m_push->getPushContent(msg_id,pContent);
break;
}
default:
break;
}
return true;
}
private:
SmsUtil* m_sms;
MmsUtil* m_mms;
PushUtil* m_push;
static MsgFacade* s_instance;
};
MsgFacade* MsgFacade::s_instance = NULL;
#include "facade.h"
int main()
{
MsgFacade* msg = MsgFacade::getInstance();
msg->checkReady(MSG_ALL);
cout<<endl;
char content[100] = {0};
msg->getMsgContent(SMS,0,content);
cout<<content<<endl;
msg->getMsgContent(MMS,0,content);
cout<<content<<endl;
msg->getMsgContent(PUSH,0,content);
cout<<content<<endl;
return 0;
}
6.flyweight享元
共享技术,支持大量细粒度对象,考虑内部状态和外部状态。将内部状态(不会发生变化的状态)与外部状态(可能发生变化的状态)分离,这样不会发生变化的部分可以抽取出来共享,而可能发生变化的部分由客户维护。
public abstract class Order
{
// 将咖啡卖给客人
public abstract void Serve(Table table);
// 返回咖啡的名字
public abstract string GetFlavor();
}
public class Flavor : Order
{
private string flavor;
// 构造函数,内蕴状态以参数方式传入
public Flavor(string flavor)
{
this.flavor = flavor;
}
// 返回咖啡的名字
public override string GetFlavor()
{
return this.flavor;
}
// 将咖啡卖给客人
public override void Serve(Table table)
{
Console.WriteLine("Serving table {0} with flavor {1}", table.Number, flavor);
}
}
public class FlavorFactory
{
private Hashtable flavors = new Hashtable();
public Order GetOrder(string key)
{
if(! flavors.ContainsKey(key))
flavors.Add(key, new Flavor(key));
return ((Order)flavors[key]);
}
public int GetTotalFlavorsMade()
{
return flavors.Count;
}
}
public class Table
{
private int number;
public Table(int number)
{
this.number = number;
}
public int Number
{
get { return number; }
}
}
public class Client
{
private static FlavorFactory flavorFactory;
private static int ordersMade = 0;
public static void Main( string[] args )
{
flavorFactory = new FlavorFactory();
TakeOrder("Black Coffee");
TakeOrder("Capucino");
TakeOrder("Espresso");
TakeOrder("Capucino");
TakeOrder("Espresso");
TakeOrder("Black Coffee");
TakeOrder("Espresso");
TakeOrder("Espresso");
TakeOrder("Black Coffee");
TakeOrder("Capucino");
TakeOrder("Capucino");
TakeOrder("Black Coffee");
Console.WriteLine("\nTotal Orders made: " + ordersMade);
Console.WriteLine("\nTotal Flavor objects made: " +
flavorFactory.GetTotalFlavorsMade());
}
private static void TakeOrder(string aFlavor)
{
Order o = flavorFactory.GetOrder(aFlavor);
// 将咖啡卖给客人
o.Serve(new Table(++ordersMade));
}
}
7.proxy代理
远程代理,虚拟代理,保护代理,智能引用代理等等。
//定义了接口 2 interface SaleTowelIntertace 3 { 4 void sellTowel(); 5 } 6 //毛巾的生产类 7 class TowelProduce : SaleTowelIntertace 8 { 9 string ConsumerName; 10 TowelProduce(string consumer_name) 11 { 12 ConsumerName = consumer_name; 13 } 14 void sellTowel() 15 { 16 Console.WriteLine("毛巾卖给了{0}",ConsumerName); 17 } 18 } 19 //卖毛巾的代理类 20 class TowelSaleProxy : SaleTowelIntertace 21 { 22 TowelProduce tp; 23 TowelSaleProxy(string consumner_name) 24 { 25 tp = new TowelProduce(consumer_name); 26 } 27 void sellTowel() 28 { 29 tp.sellTowel(); 30 } 31 }