设计模式[4] Bridge Pattern 桥接模式

来源:互联网 发布:民间借贷软件 编辑:程序博客网 时间:2024/05/07 20:11
decouple an abstraction from its implementation so that the two can vary independently" (Gamma et al.)
接口和实现分离,接口和实现的修改可以互不干扰。

参与者:
  • Abstraction   (IShape) 
    • defines the abstraction's interface.
    • maintains a reference to an object of type Implementor. 主要就是这个reference。
  • RefinedAbstraction   (CircleShape)
    • extends the interface defined by Abstraction.
  • Implementor   (IDrawingAPI)
    • defines the interface for implementation classes. This interface doesn't have to correspond exactly to Abstraction's interface; in fact the two interfaces can be quite different. Typically the Implementation interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives. 和Abstraction的接口没啥关系。
  • ConcreteImplementor   (DrawingAPI1, DrawingAPI2)
    • implements the Implementor interface and defines its concrete implementation.

using System;
 
 
/** "Implementor" */
 
interface IDrawingAPI {
    
void DrawCircle(double x, double y, double radius);
 }

 
 
/** "ConcreteImplementor" 1/2 */
 
class DrawingAPI1 : IDrawingAPI {
    
public void DrawCircle(double x, double y, double radius) 
    
{
        System.Console.WriteLine(
"API1.circle at {0}:{1} radius {2}", x, y, radius); 
    }

 }

 
 
/** "ConcreteImplementor" 2/2 */
 
class DrawingAPI2 : IDrawingAPI 
 
{
    
public void DrawCircle(double x, double y, double radius) 
    

        System.Console.WriteLine(
"API2.circle at {0}:{1} radius {2}", x, y, radius); 
    }

 }

 
 
/** "Abstraction" */
 
interface IShape {
    
void Draw();                             // low-level (i.e. Implementation-specific)
    void ResizeByPercentage(double pct);     // high-level (i.e. Abstraction-specific)
 }

 
 
/** "Refined Abstraction" */
 
class CircleShape : IShape {
    
private double x, y, radius;
    
private IDrawingAPI drawingAPI;
    
public CircleShape(double x, double y, double radius, IDrawingAPI drawingAPI) 
    
{
        
this.x = x;  this.y = y;  this.radius = radius; 
        
this.drawingAPI = drawingAPI;
    }

    
// low-level (i.e. Implementation-specific)
    public void Draw() { drawingAPI.DrawCircle(x, y, radius); }
    
// high-level (i.e. Abstraction-specific)
    public void ResizeByPercentage(double pct) { radius *= pct; }
 }

 
 
/** "Client" */
 
class BridgePattern {
    
public static void Main(string[] args) {
        IShape[] shapes 
= new IShape[2];
        shapes[
0= new CircleShape(123new DrawingAPI1());
        shapes[
1= new CircleShape(5711new DrawingAPI2());
 
        
foreach (IShape shape in shapes) {
            shape.ResizeByPercentage(
2.5);
            shape.Draw();
        }

    }

 }