Bridge Pattern

Bridge Pattern

桥接模式,引用“四人帮的话”就是 “decouple an abstraction from its implementation so that the two can vary independently”,抽象与行为分离。

说个例子
Bridge Pattern_第1张图片
客户想画图,画两种圆和矩形,每种矩形都要调用特别的划线(draw_a_line())方法,每一种圆也是。如果像上面那样,是不是感觉混乱了点?看看下面的呢。
Bridge Pattern_第2张图片
这个是不是舒服点?的确,图形和画法都存在一一对应的关系,我们完全可以把图形这个抽象和画法这个行为分离,而不需要一个画法对应多个抽象,如上面那个。

public   abstract   class  Shape
{
    
public abstract void draw();
}


// 画点和圆的方法
public   abstract   class  ShapeDrawing
{
    
public abstract void draw_a_line();
    
public abstract void draw_a_circle();
}


public   class  ShapeDrawingSingleton
{
    
private static ShapeDrawing shapedrawingSingleton;
    
    
public ShapeDrawingSingleton(ShapeDrawing shapedrawing)
    
{
        shapedrawingSingleton
=shapedrawing;
    }

    
    
public static ShapeDrawing getShapeDrawing()
    
{
        
return shapedrawingSingleton;
    }

}


// 画图方法基类
public   class  VShape  extends  Shape
{
    
public ShapeDrawing shapedrawing;
    
    
public void setShapeDrawing()
    
{
        
this.shapedrawing=ShapeDrawingSingleton.getShapeDrawing();
    }

    
    
public ShapeDrawing getShapeDrawing()
    
{
        
return this.shapedrawing;
    }

}


public   class  V1Circle  extends  VShape
{
    
public Circle(){setShapeDrawing();}
    
    
public void draw()
    
{
        
//用shapedrawing画圆
        
//shapedrawing.draw_a_circle()
    }

}


//
// V1Rectangle和V2系列参照上面的
//

public   class  DP1ShapeDrawing  extends  ShapeDrawing
{
    
public void draw_a_line(){};
    
public void draw_a_circle(){};
}


public   class  DP2ShapeDrawing  extends  ShapeDrawing
{
    
public void draw_a_line(){};
    
public void draw_a_circle(){};
}


ShapeDrawingSingleton shapedrawingSingleton
= new  ShapeDrawingSingleton( new  DP1ShapeDrawing());

V1Circle v1circle
= new  V1Circle();
v1circle.draw();

// 其他的类似于上面的




---------------------------------------------------------
专注移动开发
Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian

你可能感兴趣的:(Bridge Pattern)