I. 概要
ブリッジの役割は2つの場所をつなぐことですが、ブリッジパターンの役割もこれとよく似ていて、抽象的な部分とその部分の実装をつなぎ、デカップリングの役割を果たすことです。ブリッジングパターンは構造的なパターンです。ブリッジングは具体的なクラスをインターフェイス実装クラスから独立させ、これら2つのタイプのクラスは変更することができますが、お互いに影響を与えません。
以下は、異なる色や形を描くことを利用した例です。
第二に
まず、円を描画するためのインターフェイスを定義し、その中に1つのdrawメソッドだけを定義します。
/**
* 描画インターフェース
*/
public interface DrawInterface {
void drawCircle(int radius, int x, int y);
}
次に、Draw Circleインターフェースを実装する実装クラスが作成されます。
public class RedCircle implements DrawInterface {
@Override
public void drawCircle(int radius, int x, int y) {
Log.e(TAG, "半径の赤い円を描く:" + radius + "x座標である:" + x + "y座標を表す:" + y);
}
}
public class GreenCircle implements DrawInterface {
@Override
public void drawCircle(int radius, int x, int y) {
Log.e(TAG, "半径が緑の円を描く:" + radius + "x座標である:" + x + "y座標を指定する:" + y);
}
}
次に、draw インターフェースを通して shape 抽象クラスを作成します。
public abstract class Shape {
protected DrawInterface drawInterface;
public Shape(DrawInterface drawInterface){
this.drawInterface = drawInterface;
}
public abstract void draw();
}
次に、Shapeの具象実装クラスを作成します。
public class Circle extends Shape {
private int x, y, radius;
public Circle(DrawInterface drawInterface, int x, int y, int radius) {
super(drawInterface);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void draw() {
drawInterface.drawCircle(radius, x, y);
}
}
最後にテストが実行され、コードのプリントアウトは以下のように表示されます。
Shape redCircle = new Circle(new RedCircle(),,50);
redCircle.draw();
Log.e(TAG, "----------------------");
Shape greenCircle = new Circle(new GreenCircle(),,100);
greenCircle.draw();
第三に、まとめ
ブリッジングパターンは、システムの拡張性を大幅に向上させ、元のシステムを変更することなく、2つの変更次元のいずれかを拡張し、オープンとクローズの原則に沿って、優れた拡張性を持っており、実装の詳細は、お客様に透過的です。しかし、ブリッジングパターンを導入すると、システムの理解と設計の難易度が高くなり、導入するかどうかは具体的なロジックによります。
githubアドレス: