Skip to content

Instantly share code, notes, and snippets.

@sezemiadmin
Last active March 23, 2020 04:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sezemiadmin/8289faa39330a0b6bc238749bee33108 to your computer and use it in GitHub Desktop.
Save sezemiadmin/8289faa39330a0b6bc238749bee33108 to your computer and use it in GitHub Desktop.
GoFSamples
// 一般社員を表すクラス
class Employee {
private int wage; // 時給
private int hour; // 時間
// 給与を返すメソッド
public int getSalary() {
return this.wage * this.hour;
}
// コンストラクタ
public Employee(int wage, int hour) {
this.wage = wage;
this.hour = hour;
}
}
// 社長を表すクラス
class President {
private int fixedSalary; // 固定給
// 固定給を返すメソッド
public int getFixedSalary() {
return this.fixedSalary;
}
// コンストラクタ
public President(int fixedSalary) {
this.fixedSalary = fixedSalary;
}
}
// PresidentをEmployeeにつなぐアダプタとなるクラス
class EmpAdapter extends Employee { // Employeeを継承する
private President pre; // Presidentを集約する
// コンストラクタ
public EmpAdapter(President pre) {
super(0, 0);
this.pre = pre;
}
// オーバーライド
public int getSalary() {
return pre.getFixedSalary();
}
}
// テスト用のメインクラス
public class AdapterSample {
public static int salarySum(Employee[] emp) {
int sum = 0;
for (int i = 0; i < emp.length; i++) {
sum += emp[i].getSalary();
}
return sum;
}
public static void main(String[] args) {
// Employeeの配列を作成する
Employee[] emp = new Employee[5];
// Employeeのインスタンスを生成して配列に格納する
emp[0] = new Employee(850, 200);
emp[1] = new Employee(900, 180);
emp[2] = new Employee(880, 190);
emp[3] = new Employee(950, 220);
// Presidentのインスタンスを生成し、
// アダプタをかぶせて配列に格納する
emp[4] = new EmpAdapter(new President(1000000));
// 給与の合計値を表示する
System.out.println(AdapterSample.salarySum(emp));
}
}
// methodA()を定義したクラス
abstract class ClassA {
public abstract void methodA();
}
// ClassAクラスを実装目的で継承するクラス
class ClassAEx extends ClassA {
public void methodA() {
System.out.println("ClassAExクラスのmethodA()の実装");
}
}
// 橋を架けるクラス
class ClassAB {
private ClassA bridge;
public ClassAB(ClassAEx aex) {
this.bridge = aex;
}
public void methodA() {
// 集約したClassAクラスを使ってmethodA()メソッドを呼び出す
this.bridge.methodA();
}
}
// ClassAクラスと同じ機能のClassABクラスを拡張目的で継承するクラス
class ClassB extends ClassAB {
public ClassB(ClassAEx aex) {
super(aex);
}
public void methodB() {
System.out.println("ClassBクラスのmethodB()の実装");
}
}
// メインクラス
public class BridgeSample {
public static void main(String[] args) {
// 実装目的で継承したクラスのインスタンスを使う
System.out.println("<< ClassAExを使う >>");
ClassAEx aex = new ClassAEx();
aex.methodA();
// 拡張目的で継承したクラスのインスタンスを使う
System.out.println("<< ClassBを使う >>");
ClassB b = new ClassB(aex);
b.methodA(); // ここで橋を渡っている
b.methodB();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment