个人理解:
桥接模式的精髓在于维护一个抽象对象,并抽取这个对象的抽象部分。
UML类图:
代码实现:
public interface IComponent
{
void Operation();
}
public class ComponentA : IComponent
{
public void Operation()
{
Console.WriteLine("This is A...");
}
}
public class ComponentB : IComponent
{
public void Operation()
{
Console.WriteLine("This is B...");
}
}
public abstract class Abstraction:IComponent
{
protected IComponent component;
public Abstraction(IComponent component)
{
this.component = component;
}
public abstract void Operation();
}
public class ConcreteAbstraction : Abstraction
{
public ConcreteAbstraction(IComponent component)
: base(component)
{ }
public override void Operation()
{
this.component.Operation();
}
}
Python代码实现:
class Chinese(object):
def Say(self):
raise NotImplementedError("say abstract")
class NorthChinese(object):
def Say(self):
print "your elder-grandpa"
class ShanghaiChinese(object):
def Say(self):
print "small second old"
class Manager(object):
def ManageSay(self):
raise NotImplementedError("say abstract")
class ChineseManager(Manager):
__chinese=None
def __init__(self, chinese):
self.__chinese=chinese
def ManageSay(self):
self.__chinese.Say()
if __name__ == "__main__":
manager1=ChineseManager(NorthChinese())
manager2=ChineseManager(ShanghaiChinese())
manager1.ManageSay()
manager2.ManageSay()