- 浏览: 664352 次
文章分类
最新评论
c# 设计模式(2)结构型
名称 |
Adapter |
结构 |
|
意图 |
将一个类的接口转换成客户希望的另外一个接口。A d a p t e r 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。 |
适用性 |
|
Code Example |
namespace Adapter_DesignPattern
{
using System;
class FrameworkXTarget
{
virtual public void SomeRequest(int x)
{
// normal implementation of SomeRequest goes here
}
}
class FrameworkYAdaptee
{
public void QuiteADifferentRequest(string str)
{
Console.WriteLine("QuiteADifferentRequest = {0}", str);
}
}
class OurAdapter : FrameworkXTarget
{
private FrameworkYAdaptee adaptee = new FrameworkYAdaptee();
override public void SomeRequest(int a)
{
string b;
b = a.ToString();
adaptee.QuiteADifferentRequest(b);
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
void GenericClientCode(FrameworkXTarget x)
{
// We assume this function contains client-side code that only
// knows about FrameworkXTarget.
x.SomeRequest(4);
// other calls to FrameworkX go here
// ...
}
public static int Main(string[] args)
{
Client c = new Client();
FrameworkXTarget x = new OurAdapter();
c.GenericClientCode(x);
return 0;
}
}
}
|
名称 |
Bridge |
结构 |
|
意图 |
将抽象部分与它的实现部分分离,使它们都可以独立地变化。 |
适用性 |
|
Code Example |
namespace Bridge_DesignPattern
{
using System;
class Abstraction
{
protected Implementation impToUse;
public void SetImplementation(Implementation i)
{
impToUse = i;
}
virtual public void DumpString(string str)
{
impToUse.DoStringOp(str);
}
}
class DerivedAbstraction_One : Abstraction
{
override public void DumpString(string str)
{
str += ".com";
impToUse.DoStringOp(str);
}
}
class Implementation
{
public virtual void DoStringOp(string str)
{
Console.WriteLine("Standard implementation - print string as is");
Console.WriteLine("string = {0}", str);
}
}
class DerivedImplementation_One : Implementation
{
override public void DoStringOp(string str)
{
Console.WriteLine("DerivedImplementation_One - don't print string");
}
}
class DerivedImplementation_Two : Implementation
{
override public void DoStringOp(string str)
{
Console.WriteLine("DerivedImplementation_Two - print string twice");
Console.WriteLine("string = {0}", str);
Console.WriteLine("string = {0}", str);
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
Abstraction SetupMyParticularAbstraction()
{
// we localize to this method the decision which abstraction and
// which implementation to use. These need to be decided
// somewhere and we do it here. All teh rest of the client
// code can work against the abstraction object.
Abstraction a = new DerivedAbstraction_One();
a.SetImplementation(new DerivedImplementation_Two());
return a;
}
public static int Main(string[] args)
{
Client c = new Client();
Abstraction a = c.SetupMyParticularAbstraction();
// From here on client code thinks it is talking to the
// abstraction, and will not need to be changed as
// derived abstractions are changed.
// more client code using the abstraction goes here
// . . .
a.DumpString("Clipcode");
return 0;
}
}
}
|
名称 |
Composite |
结构 |
|
意图 |
将对象组合成树形结构以表示“部分-整体”的层次结构。C o m p o s i t e 使得用户对单个对象和组合对象的使用具有一致性。 |
适用性 |
|
Code Example |
namespace FactoryMethod_DesignPattern
{
using System;
using System.Collections;
abstract class Component
{
protected string strName;
public Component(string name)
{
strName = name;
}
abstract public void Add(Component c);
public abstract void DumpContents();
// other operations for delete, get, etc.
}
class Composite : Component
{
private ArrayList ComponentList = new ArrayList();
public Composite(string s) : base(s) {}
override public void Add(Component c)
{
ComponentList.Add(c);
}
public override void DumpContents()
{
// First dump the name of this composite node
Console.WriteLine("Node: {0}", strName);
// Then loop through children, and get then to dump their contents
foreach (Component c in ComponentList)
{
c.DumpContents();
}
}
}
class Leaf : Component
{
public Leaf(string s) : base(s) {}
override public void Add(Component c)
{
Console.WriteLine("Cannot add to a leaf");
}
public override void DumpContents()
{
Console.WriteLine("Node: {0}", strName);
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
Component SetupTree()
{
// here we have to create a tree structure,
// consisting of composites and leafs.
Composite root = new Composite("root-composite");
Composite parentcomposite;
Composite composite;
Leaf leaf;
parentcomposite = root;
composite = new Composite("first level - first sibling - composite");
parentcomposite.Add(composite);
leaf = new Leaf("first level - second sibling - leaf");
parentcomposite.Add(leaf);
parentcomposite = composite;
composite = new Composite("second level - first sibling - composite");
parentcomposite.Add(composite);
composite = new Composite("second level - second sibling - composite");
parentcomposite.Add(composite);
// we will leaf the second level - first sibling empty, and start
// populating the second level - second sibling
parentcomposite = composite;
leaf = new Leaf("third level - first sibling - leaf");
parentcomposite.Add(leaf);
leaf = new Leaf("third level - second sibling - leaf");
parentcomposite.Add(leaf);
composite = new Composite("third level - third sibling - composite");
parentcomposite.Add(composite);
return root;
}
public static int Main(string[] args)
{
Component component;
Client c = new Client();
component = c.SetupTree();
component.DumpContents();
return 0;
}
}
}
|
名称 |
Decorator |
结构 |
|
意图 |
动态地给一个对象添加一些额外的职责。就增加功能来说,D e c o r a t o r 模式相比生成子类更为灵活。 |
适用性 |
|
Code Example |
namespace Decorator_DesignPattern
{
using System;
abstract class Component
{
public abstract void Draw();
}
class ConcreteComponent : Component
{
private string strName;
public ConcreteComponent(string s)
{
strName = s;
}
public override void Draw()
{
Console.WriteLine("ConcreteComponent - {0}", strName);
}
}
abstract class Decorator : Component
{
protected Component ActualComponent;
public void SetComponent(Component c)
{
ActualComponent = c;
}
public override void Draw()
{
if (ActualComponent != null)
ActualComponent.Draw();
}
}
class ConcreteDecorator : Decorator
{
private string strDecoratorName;
public ConcreteDecorator (string str)
{
// how decoration occurs is localized inside this decorator
// For this demo, we simply print a decorator name
strDecoratorName = str;
}
public override void Draw()
{
CustomDecoration();
base.Draw();
}
void CustomDecoration()
{
Console.WriteLine("In ConcreteDecorator: decoration goes here");
Console.WriteLine("{0}", strDecoratorName);
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
Component Setup()
{
ConcreteComponent c = new ConcreteComponent("This is the real component");
ConcreteDecorator d = new ConcreteDecorator("This is a decorator for the component");
d.SetComponent(c);
return d;
}
public static int Main(string[] args)
{
Client client = new Client();
Component c = client.Setup();
// The code below will work equally well with the real component,
// or a decorator for the component
c.Draw();
return 0;
}
}
}
|
名称 |
Facade |
结构 |
|
意图 |
为子系统中的一组接口提供一个一致的界面,F a c a d e 模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。 |
适用性 |
|
Code Example |
namespace Facade_DesignPattern
{
using System;
class SubSystem_class1
{
public void OperationX()
{
Console.WriteLine("SubSystem_class1.OperationX called");
}
}
class SubSystem_class2
{
public void OperationY()
{
Console.WriteLine("SubSystem_class2.OperationY called");
}
}
class SubSystem_class3
{
public void OperationZ()
{
Console.WriteLine("SubSystem_class3.OperationZ called");
}
}
class Facade
{
private SubSystem_class1 c1 = new SubSystem_class1();
private SubSystem_class2 c2 = new SubSystem_class2();
private SubSystem_class3 c3 = new SubSystem_class3();
public void OperationWrapper()
{
Console.WriteLine("The Facade OperationWrapper carries out complex decision-making");
Console.WriteLine("which in turn results in calls to the subsystem classes");
c1.OperationX();
if (1==1 /*some really complex decision*/)
{
c2.OperationY();
}
// lots of complex code here . . .
c3.OperationZ();
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
public static int Main(string[] args)
{
Facade facade = new Facade();
Console.WriteLine("Client calls the Facade OperationWrapper");
facade.OperationWrapper();
return 0;
}
}
}
|
名称 |
Flyweight |
结构 |
|
意图 |
运用共享技术有效地支持大量细粒度的对象。 |
适用性 |
|
Code Example |
namespace Flyweight_DesignPattern
{
using System;
using System.Collections;
class FlyweightFactory
{
private ArrayList pool = new ArrayList();
// the flyweightfactory can crete all entries in the pool at startup
// (if the pool is small, and it is likely all will be used), or as
// needed, if the pool si large and it is likely some will never be used
public FlyweightFactory()
{
pool.Add(new ConcreteEvenFlyweight());
pool.Add(new ConcreteUnevenFlyweight());
}
public Flyweight GetFlyweight(int key)
{
// here we would determine if the flyweight identified by key
// exists, and if so return it. If not, we would create it.
// As in this demo we have implementation all the possible
// flyweights we wish to use, we retrun the suitable one.
int i = key % 2;
return((Flyweight)pool[i]);
}
}
abstract class Flyweight
{
abstract public void DoOperation(int extrinsicState);
}
class UnsharedConcreteFlyweight : Flyweight
{
override public void DoOperation(int extrinsicState)
{
}
}
class ConcreteEvenFlyweight : Flyweight
{
override public void DoOperation(int extrinsicState)
{
Console.WriteLine("In ConcreteEvenFlyweight.DoOperation: {0}", extrinsicState);
}
}
class ConcreteUnevenFlyweight : Flyweight
{
override public void DoOperation(int extrinsicState)
{
Console.WriteLine("In ConcreteUnevenFlyweight.DoOperation: {0}", extrinsicState);
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
public static int Main(string[] args)
{
int[] data = {1,2,3,4,5,6,7,8};
FlyweightFactory f = new FlyweightFactory();
int extrinsicState = 3;
foreach (int i in data)
{
Flyweight flyweight = f.GetFlyweight(i);
flyweight.DoOperation(extrinsicState);
}
return 0;
}
}
}
|
名称 |
Proxy |
结构 |
|
意图 |
为其他对象提供一种代理以控制对这个对象的访问。 |
适用性 |
|
Code Example |
namespace Proxy_DesignPattern
{
using System;
using System.Threading;
/// <summary>
/// Summary description for Client.
/// </summary>
abstract class CommonSubject
{
abstract public void Request();
}
class ActualSubject : CommonSubject
{
public ActualSubject()
{
// Assume constructor here does some operation that takes quite a
// while - hence the need for a proxy - to delay incurring this
// delay until (and if) the actual subject is needed
Console.WriteLine("Starting to construct ActualSubject");
Thread.Sleep(1000); // represents lots of processing!
Console.WriteLine("Finished constructing ActualSubject");
}
override public void Request()
{
Console.WriteLine("Executing request in ActualSubject");
}
}
class Proxy : CommonSubject
{
ActualSubject actualSubject;
override public void Request()
{
if (actualSubject == null)
actualSubject = new ActualSubject();
actualSubject.Request();
}
}
public class Client
{
public static int Main(string[] args)
{
Proxy p = new Proxy();
// Perform actions here
// . . .
if (1==1) // at some later point, based on a condition,
p.Request();// we determine if we need to use subject
return 0;
}
}
}
|
相关推荐
C#设计模式-结构型相关课件 合成模式(Composite) • 设计方案一: 合成模式(Composite) • 设计方案二 合成模式(Composite) • 设计方案一和设计方案二的区别 – 设计方案二使得客户端更不需要关心所需处理的...
C#面向对象设计模式纵横谈(8):Bridge 桥接模式(结构型模式) 体验课程
《C#设计模式》由James W. Cooper编著,主要介绍如何用最常见的设计模式编写C#程序。全书分为4个部分,首先介绍了C#语言和面向对象程序设计的一般原则,可作为C#程序设计的快速入门教程;然后分别讲述了创建型模式、...
C#面向对象设计模式纵横谈(9):Composite 组合模式(结构型模式)
C#面向对象设计模式纵横谈(11):Facade 外观模式(结构型模式) (Level 300)
C#面向对象设计模式纵横谈(7):Adapter 适配器模式(结构型模式) C#面向对象设计模式纵横谈(8):Bridge 桥接模式(结构型模式) C#面向对象设计模式纵横谈(9):Composite 组合模式(结构型模式) C#面向对象设计模式...
本书主要介绍如何用最常见的设计模式编写C#程序。全书分为四个部分,首先介绍了C#语言和面向对象程序设计的一般原则,可作为C#程序设计的快速入门教程;然后分别讲述了创建型模式、结构型模式和行为型模式。每一类...
C#面向对象设计模式纵横谈(25):设计模式总结
原型模式(Prototype)结构型: 6. 适配器模式(Adapter Pattern) 7. 桥接模式(Bridge Pattern) 8. 装饰模式(Decorator Pattern) 9. 组合模式(Composite Pattern) 10. 外观模式(Facade Pattern) 11. 享元模式...
总体来说设计模式分为三大类: 创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。 结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元...
C#面向对象设计模式纵横谈(8):Bridge 桥接模式(结构型模式) (Level 300)
C#设计模式,适合初学者,讲了创建,型行为型,结构型模型
C#23种设计模式样例代码和UML图等 创建型模式(抽象工厂模式、工厂方法模式、单例模式、建造者模式、原型模式); 行为型模式(策略模式、 迭代器模式、原型模式、职责链模式、 模板方法、 命令模式、 解释器模式、 ...
包含以下文章所有代码及测试: C# .Net设计模式与代码实现(一)——创建型模式 C# .Net设计模式与代码实现(二)——结构型模式 C# .Net设计模式与代码实现(三)——行为型模式
1.桥接模式:电子商务网站常有这样的功能:发送消息通知,比如订货发货通知等,从业务上看,消息分为普通消息、加急消息和特急消息多种不同的消息类型,其业务处理是不一样的,比如加急消息是在消息上添加加急标记.....
C#面向对象设计模式纵横谈(12):Flyweight 享元模式(结构型模式) (Level 300)
C#面向对象设计模式纵横谈(13):Proxy 代理模式(结构型模式)
本书主要介绍如何用最常见的设计模式编写C#程序。全书分为四个部分,首先介绍了C#语言和面向对象程序设计的一般原则,可作为C#程序设计的快速入门教程;然后分别讲述了创建型模式、结构型模式和行为型模式。每一类...
[美]James W.Cooper 著 第一部分 C#面向对象程序设计 第二部分 创建型模式 第三部分 结构型模式 第四部分 行为型模式