一 、 另外一个实际应用 Bridge 模式的例子
该例子演示了业务对象(BusinessObject)通过 Bridge 模式与数据对象(DataObject)解耦。数据对象的实现可以在不改变客户端代码的情况下动态进行更换。
[C#] 纯文本查看 复制代码 // Bridge pattern -- Real World example
using System;
using System.Collections;
// "Abstraction"
class BusinessObject
{
// Fields
private DataObject dataObject;
protected string group;
// Constructors
public BusinessObject(string group)
{
this.group = group;
}
// Properties
public DataObject DataObject
{
set { dataObject = value; }
get { return dataObject; }
}
// Methods
public virtual void Next()
{ dataObject.NextRecord(); }
public virtual void Prior()
{ dataObject.PriorRecord(); }
public virtual void New(string name)
{ dataObject.NewRecord(name); }
public virtual void Delete(string name)
{ dataObject.DeleteRecord(name); }
public virtual void Show()
{ dataObject.ShowRecord(); }
public virtual void ShowAll()
{
Console.WriteLine("Customer Group: {0}", group);
dataObject.ShowAllRecords();
}
}
// "RefinedAbstraction"
class CustomersBusinessObject : BusinessObject
{
// Constructors
public CustomersBusinessObject(string group) : base(group) { }
// Methods
public override void ShowAll()
{
// Add separator lines
Console.WriteLine();
Console.WriteLine("------------------------");
base.ShowAll();
Console.WriteLine("------------------------");
}
}
// "Implementor"
abstract class DataObject
{
// Methods
public abstract void NextRecord();
public abstract void PriorRecord();
public abstract void NewRecord(string name);
public abstract void DeleteRecord(string name);
public abstract void ShowRecord();
public abstract void ShowAllRecords();
}
// "ConcreteImplementor"
class CustomersDataObject : DataObject
{
// Fields
private readonly ArrayList customers = new ArrayList();
private int current;
// Constructors
public CustomersDataObject()
{
// Loaded from a database
customers.Add("Jim Jones");
customers.Add("Samual Jackson");
customers.Add("Allen Good");
customers.Add("Ann Stills");
customers.Add("Lisa Giolani");
}
// Methods
public override void NextRecord()
{
if (current <= customers.Count - 1)
current++;
}
public override void PriorRecord()
{
if (current > 0)
current--;
}
public override void NewRecord(string name)
{
customers.Add(name);
}
public override void DeleteRecord(string name)
{
customers.Remove(name);
}
public override void ShowRecord()
{
Console.WriteLine(customers[current]);
}
public override void ShowAllRecords()
{
foreach (string name in customers)
Console.WriteLine(" " + name);
}
}
/// <summary>
/// Client test
/// </summary>
public class BusinessApp
{
public static void Main(string[] args)
{
// Create RefinedAbstraction
CustomersBusinessObject customers = new CustomersBusinessObject(" Chicago ") { DataObject = new CustomersDataObject() };
// Set ConcreteImplementor
// Exercise the bridge
customers.Show();
customers.Next();
customers.Show();
customers.Next();
customers.Show();
customers.New("Henry Velasquez");
customers.ShowAll();
}
}
|