zoukankan      html  css  js  c++  java
  • 设计模式--桥接模式

    将抽象部分与它的实现部分分离,使它们都可以独立地变化。
    抽象与它的实现分离,并不是说让抽象类与其派生类分离,因为这没有任何意义,实现指的是抽象类和它的派生类用来实现自己的对象。

    实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。

    基本代码:

    //抽象基类

    class Abstraction
    {
    protected Implementor implementor;
    public void SetImpementor(Implementor implementor)
    {
    this.implementor = implementor;
    }

    public virtual void Operation()
    {
    implementor.Operation();
    }

    }

    //抽象基类的一个实现

    class RefinedAbstraction:Abstraction
    {
    public override void Operation()
    {
    implementor.Operation();
    }
    }

    //具体实现的基类

    abstract class Implementor
    {
    public abstract void Operation();
    }

    //具体实现

    class ConcreteImplementorA : Implementor
    {
    public override void Operation()
    {
    Console.WriteLine("具体实现A的方法执行");
    }
    }

    class ConcreteImplementorB : Implementor
    {
    public override void Operation()
    {
    Console.WriteLine("具体实现B的方法执行");
    }
    }

    调用:

    Abstraction ab = new RefinedAbstraction();
    ab.SetImpementor(new ConcreteImplementorA());
    ab.Operation();

    ab.SetImpementor(new ConcreteImplementorB());
    ab.Operation();

    //松耦合的程序

    //手机软件抽象类

    abstract class HandsetSoft
    {
    public virtual void Run(HandsetBrand hb)
    {
    Console.Write(hb.GetType().Name+":");
    }
    }

    //手机游戏

    class HandsetGame:HandsetSoft
    {
    public override void Run(HandsetBrand hb)
    {
    base.Run(hb);
    Console.WriteLine("运行手机游戏");
    }
    }

    //手机通讯录

    class HandsetAddressList:HandsetSoft
    {
    public override void Run(HandsetBrand hb)
    {
    base.Run(hb);
    Console.WriteLine("运行手机通讯录");
    }
    }

    //手机品牌抽象类

    abstract class HandsetBrand
    {
    protected HandsetSoft soft;
    public void SetHandsetSoft(HandsetSoft soft)
    {
    this.soft = soft;
    }
    public virtual void Run(HandsetBrand hb)
    {
    this.soft.Run(hb);
    }
    }

    //手机品牌M

    class HandsetBrandM:HandsetBrand
    {
    }

    //手机品牌N

    class HandsetBrandN:HandsetBrand
    {
    }

    调用:

    HandsetGame game = new HandsetGame();
    HandsetAddressList addressList = new HandsetAddressList();

    HandsetBrand hb = new HandsetBrandM();
    hb.SetHandsetSoft(game);
    hb.Run(hb);
    hb.SetHandsetSoft(addressList);
    hb.Run(hb);

    hb = new HandsetBrandN();
    hb.SetHandsetSoft(game);
    hb.Run(hb);
    hb.SetHandsetSoft(addressList);
    hb.Run(hb);

  • 相关阅读:
    HDU 3586 Information Disturbing (树形DP+二分)
    HDU 6053 TrickGCD (莫比乌斯函数)
    51Nod 1554 欧姆诺姆和项链 (KMP)
    HDU 6153 A Secret (KMP)
    HDU 6156 Palindrome Function (数位DP)
    HDU 6148 Valley Numer (数位DP)
    UVa 1513 Movie collection (树状数组)
    HDU 6125 Free from square (状压DP+背包)
    UVa 10766 Organising the Organisation (生成树计数)
    tensorflow 待阅读的资料
  • 原文地址:https://www.cnblogs.com/buzhidaojiaoshenme/p/6731478.html
Copyright © 2011-2022 走看看