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