- 桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。
例子:
例:模拟毛笔:
现需要提供大中小3种型号的画笔,能够绘制5种不同颜色,如果使用蜡笔,我们需要准备3*5=15支蜡笔,也就是说必须准备15个具体的蜡笔类。而如果使用毛笔的话,只需要3种型号的毛笔,外加5个颜料盒,用3+5=8个类就可以实现15支蜡笔的功能。使用桥接模式设计和实现来模拟毛笔的使用过程。
类图:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 桥接模式
{
class Program
{
static void Main(string[] args)
{
ChPen pen;
Color c = new white();
pen = new sPen();
pen.Draw(c);
pen = new mPen();
pen.Draw(c);
pen = new lpen();
pen.Draw(c);
Console.ReadKey();
}
}
interface Color
{
void Dye();//着色
}
interface ChPen
{
void Draw(Color color);
}
class sPen:ChPen
{
public static string type = "小号毛笔";
public void Draw(Color color)
{
color = new white();
color.Dye();
Console.WriteLine("{0}绘画",sPen.type);
color = new black();
color.Dye();
Console.WriteLine("{0}绘画", sPen.type);
color = new yellow();
color.Dye();
Console.WriteLine("{0}绘画", sPen.type);
color = new green();
color.Dye();
Console.WriteLine("{0}绘画", sPen.type);
color = new red();
color.Dye();
Console.WriteLine("{0}绘画", sPen.type);
}
}
class mPen:ChPen
{
public static string type = "中号毛笔";
public void Draw(Color color)
{
color = new white();
color.Dye();
Console.WriteLine("{0}绘画", mPen.type);
color = new black();
color.Dye();
Console.WriteLine("{0}绘画", mPen.type);
color = new yellow();
color.Dye();
Console.WriteLine("{0}绘画", mPen.type);
color = new green();
color.Dye();
Console.WriteLine("{0}绘画", mPen.type);
color = new red();
color.Dye();
Console.WriteLine("{0}绘画", mPen.type);
}
}
class lpen:ChPen
{
public static string type = "大号毛笔";
public void Draw(Color color)
{
color = new white();
color.Dye();
Console.WriteLine("{0}绘画", lpen.type);
color = new black();
color.Dye();
Console.WriteLine("{0}绘画", lpen.type);
color = new yellow();
color.Dye();
Console.WriteLine("{0}绘画", lpen.type);
color = new green();
color.Dye();
Console.WriteLine("{0}绘画", lpen.type);
color = new red();
color.Dye();
Console.WriteLine("{0}绘画", lpen.type);
}
}
class red : Color
{
public static string color = "红色";
public void Dye()
{
Console.WriteLine("着色{0}", red.color);
}
}
class green : Color
{
public static string color = "黄色";
public void Dye()
{
Console.WriteLine("着色{0}", green.color);
}
}
class yellow : Color
{
public static string color = "黄色";
public void Dye()
{
Console.WriteLine("着色{0}",yellow.color);
}
}
class black : Color
{
public static string color = "黑色";
public void Dye()
{
Console.WriteLine("着色{0}", black.color);
}
}
class white:Color
{
public static string color = "白色";
public void Dye()
{
Console.WriteLine("着色{0}", white.color);
}
}
}
如有错误之处还请指正!