分离接口与实现,以实现替换实现时不必修改客户端。
Abstraction(BusinessObject)
定义类的接口;
RefinedAbstraction(CustomerBusinessObject)
扩展接口;
Implementor(DataObject)
定义实现类的接口,这个接口可以不和Abstraction接口吻合,实际上会完全不同。实现类的接口提供基础的操作,而Abstraction定义基于基础操作的高层操作。
ConcreteImplementor(CustomersDataObject)
实现Implementor接口和定义它自己具体实现。
代码:
//Abstraction
public abstract class BusinessObject{
//Fields
private DataObject dataObject;
protected String group;
public BusinessObject(String group){
this.group=group;
}
public DataObject getDataObject(){
return dataObject;
}
public void setDataObject(DataObject value){
dataObject=value;
}
public void Next(){
dataObject.NextRecord();
}
public void Prior(){
dataObject.PriorRecord();
}
public void New(String name){
dataObject.NewRecord(name);
}
public void Delete(String name){
dataObject.DeleteRecord(name);
}
public void Show(){
dataObject.ShowRecord();
}
public void ShowAll(){
System.out.println(“Customer Group:”+group);
dataObject.ShowAllRecords();
}
}
//RefinedAbstraction
public class CustomerBusinessObject extends BusinessObject{
public CustomerBusinessObject(String group){
super(group);
}
public void ShowAll(){
System.out.println(“--------------------”);
super.ShowAll();
System.out.println(“--------------------“);
}
}
//Implementor
public interface DataObject{
public void NextRecord();
public void PriorRecord();
public void NewRecord(String name);
public void DeleteRecord(String name);
public void ShowRecord();
public void ShowAllRecords();
}
//ConcreteImplementor
package org.colimas.doxygen.qtools;
import java.util.*;
public class CustomersDataObject implements DataObject {
private ArrayList customers=new ArrayList();
private int current = 0;
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" );
}
public void NextRecord() {
if( current <= customers.size()-1)
current++;
}
public void PriorRecord() {
if( current > 0 )
current--;
}
public void NewRecord(String name) {
customers.add( name );
}
public void DeleteRecord(String name) {
customers.remove( name );
}
public void ShowRecord() {
System.out.println(customers.get(current).toString());
}
public void ShowAllRecords() {
for (int i=0;i<customers.size();i++)
System.out.println(customers.get(i).toString());
}
}
//Client
public class BusinessApp {
public static void main(String[] args) {
BusinessObject customers =
new CustomerBusinessObject("Chicago");
//Set ConcreteImplementor
customers.setDataObject(new CustomersDataObject());
//Exercise the bridge
customers.Show();
customers.Next();
customers.Show();
customers.Next();
customers.Show();
customers.New( "Henry Velasquez" );
customers.ShowAll();
}
}
Output
Jim Jones
Samual Jackson
Allen Good
------------------------
Customer Group: Chicago
Jim Jones
Samual Jackson
Allen Good
Ann Stills
Lisa Giolani
Henry Velasquez
------------------------