C# 设计模式 之 桥接模式

       桥接模式关注如何设计抽象类!
       主要目的是把一个抽象类与其抽象操作的实现进行分离。
       抽象类处于类层次结构的顶层位置,它定义了抽象的操作集,层次结构中的某些子类都为抽象操作集提供了不同的实现,这些操作集在一个接口中,另外还有子类沿着另外的方向,整个设计就是需要使用桥接模式。简单的说,处于顶层位置的抽象类的继承出现多方向,需要使用桥接模式。

using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Bridge
{
    
/// <summary>
    
/// 打印方式
    
/// </summary>

    public abstract class PrintMethod
    
{
        
public abstract void Print();
    }


    
/// <summary>
    
/// 横向方式
    
/// </summary>

    public class Across : PrintMethod
    
{
        
public override void Print()
        
{

            Console.WriteLine(
"--");
        }

    }


    
/// <summary>
    
/// 纵向方式
    
/// </summary>

    public class Upright : PrintMethod
    
{
        
public override void Print()
        
{
            Console.WriteLine(
"|");
        }

    }


    
/// <summary>
    
/// 机器
    
/// </summary>

    public abstract class Machine
    
{
        
protected PrintMethod implementor;

        
public PrintMethod Implementor
        
{
            
set { implementor = value; }
        }


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

    }


    
/// <summary>
    
/// 打印机
    
/// </summary>

    public class Printer : Machine
    
{
        
public override void Print()
        
{
            implementor.Print();
        }

    }


    
/// <summary>
    
/// 复印机
    
/// </summary>

    public class Copycat : Machine
    
{
        
public override void Print()
        
{
            implementor.Print();
        }

    }


    
class Program
    
{
        
static void Main(string[] args)
        
{
            Machine machine 
= new Printer();
            machine.Implementor 
= new Across();
            machine.Print();

            machine 
= new Copycat();
            machine.Implementor 
= new Upright();
            machine.Print();

            Console.ReadLine();
        }

    }

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值