合成(組合)/聚合複用原則
阿新 • • 發佈:2019-01-01
1.定義:儘量使用物件組合/聚合,而不是繼承關係達到軟體複用的目的
2.聚合has-A和組合contains-A
3.優點:可以使系統更加靈活,降低類與類之間的耦合度,一個類的變化對其他類造成的影響相對較少
4.思考:何時使用合成/聚合、繼承?聚合has-A、組合contains-A、繼承is-A
5.例項目錄package
6.例項UML類圖
7.程式碼
1 package com.geely.design.principle.compositionaggregation; 2 3 public abstract class DBConnection { 4 /*public String getConnection(){ 5 return "MySQL資料庫連線"; 6 }*/ 7 public abstract String getConnection(); 8 }
1 package com.geely.design.principle.compositionaggregation; 2 3 public class MySQLConnection extends DBConnection{ 4 public String getConnection() { 5 return "MySQL資料庫連線";6 } 7 }
1 package com.geely.design.principle.compositionaggregation; 2 3 public class PostgreSQLConnection extends DBConnection { 4 public String getConnection() { 5 return "PostgreSQL資料庫連線"; 6 } 7 }
1 package com.geely.design.principle.compositionaggregation; 2 3public class ProductDao{// extends DBConnection 4 private DBConnection dbConnection; 5 6 public void setDbConnection(DBConnection dbConnection) { 7 this.dbConnection = dbConnection; 8 } 9 10 public void addProduct(){ 11 String conn = dbConnection.getConnection(); 12 System.out.println("使用"+conn + "增加產品"); 13 } 14 }
1 package com.geely.design.principle.compositionaggregation; 2 3 public class Test { 4 public static void main(String[] args) { 5 ProductDao productDao = new ProductDao(); 6 productDao.setDbConnection(new MySQLConnection()); 7 productDao.addProduct(); 8 productDao.setDbConnection(new PostgreSQLConnection()); 9 productDao.addProduct(); 10 } 11 }