标签:sys sql style this extend set connect return post
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 3 public 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 }
标签:sys sql style this extend set connect return post
原文地址:https://www.cnblogs.com/linbq1911/p/10205088.html