适配器模式

将一个类的接口转化成客户希望的另外一个接口,Adapter模式使得原本由于接口不兼容而不能一起工作的那些类在一起工作。

  1. class Target{
  2. public void Request(){
  3. Console.WriteLine("普通请求!");
  4. }
  5. }
  6. class Adaptee{
  7. public void SpecificRequest(){
  8. Console.WriteLine("特殊需求!");
  9. }
  10. }
  11. class Adapter:Target{
  12. private Adaptee adaptee=new Adaptee();
  13. public void Request(){
  14. adaptee.SpecificRequest();
  15. }
  16. }
  17. //console
  18. Target target=new Adapter();
  19. //表面上调用Request实际调用SpecificRequest.
  20. target.Request();

桥接模式

  1. //手机软件
  2. interface HandsetSoft{
  3. public void Run();
  4. }
  5. //手机游戏
  6. class HandsetGame:HandsetSoft{
  7. public void Run(){
  8. Console.WriteLine("运行手机游戏");
  9. }
  10. }
  11. //手机通讯录
  12. class HandsetAddressList:HandsetSoft{
  13. public void Run(){
  14. Console.WriteLine("运行手机通讯录");
  15. }
  16. }
  17. //手机品牌
  18. interface HandsetBrand{
  19. protected HandsetSoft soft;
  20. //设置手机软件
  21. public void setHandsetSoft(HandsetSoft soft){
  22. this.soft=soft;
  23. }
  24. //运行
  25. public void Run();
  26. }
  27. //具体的手机品牌
  28. class HandsetBrandN:HandsetBrand{
  29. public void Run(){
  30. soft.Run();
  31. }
  32. }
  33. //以上代码实现了对扩展开放的原则,如果新增加手机软件或者手机品牌都只需要增加相应的类即可,
  34. //不需要修改原有代码.

桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立变化。

  1. interface Implementor{
  2. public void Operation();
  3. }
  4. class ConcreteImplementorA:Implementor{
  5. public void Operation(){
  6. Console.WriteLine("具体实现A的方法执行");
  7. }
  8. }
  9. class ConcreteImplementorB:Implementor{
  10. public void Operation(){
  11. Console.WriteLine("具体实现B的方法执行");
  12. }
  13. }
  14. class Abstraction{
  15. protected Implementor implementor;
  16. public void SetImplementor(Implementor implementor){
  17. this.implementor=implementor;
  18. }
  19. public void Operation(){
  20. implementor.Operation();
  21. }
  22. }
  23. class RefinedAbstraction:Abstraction{
  24. public void Operation(){
  25. implementor.Operation();
  26. }
  27. }
  28. //以上代码实现了:实现系统可能有多角度分类,每一种分类都有可能变化,
  29. //那么就把这种多角度分离出来让它们独立变化,减少它们的耦合.

组合模式

组合模式:将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。

装饰模式

代理模式

外观模式

享元模式