zoukankan      html  css  js  c++  java
  • 设计模式七大原则——迪米特原则以及设计原则的核心思想

    一、基本介绍

      尽量使用合成/聚合的方式,而不是使用继承

    二、应用实例

      

       此处有两个类,A类和B类,然后我们接到一个需求,需要在B类中使用到A类的方法

      解决方案1:直接让B类继承A类

      

      代码实现:

     1 public class A {
     2     void operation1(){
     3         //do something...
     4     }
     5 
     6     void operation2(){
     7         //do something...
     8     }
     9 }
    10 
    11 class B extends A{
    12     @Override
    13     void operation1() {
    14         super.operation1();
    15     }
    16 
    17     @Override
    18     void operation2() {
    19         super.operation2();
    20     }
    21 }

       分析:如果只是让B类去使用A类中的方法,使用继承就会让B类和A类之间的耦合性增强(一旦A类发生任何变动就会影响到B类),可以使用合成/聚合的方式替代继承

      解决方案2:让A类作为B类方法的参数来实现依赖关系

      

      代码实现:

     1 public class A {
     2     void operation1() {
     3         //do something...
     4     }
     5 
     6     void operation2() {
     7         //do something...
     8     }
     9 }
    10 
    11 class B {
    12     void operation1(A a) {
    13         a.operation1();
    14         a.operation2();
    15     }
    16 }

      解决方案3:将A类的实例作为B类的成员变量来实现聚合关系

      

      代码实现:

     1 public class A {
     2     void operation1() {
     3         //do something...
     4     }
     5 
     6     void operation2() {
     7         //do something...
     8     }
     9 }
    10 
    11 class B {
    12     private A a;
    13 
    14     public void setA(A a) {
    15         this.a = a;
    16     }
    17 }

      解决方案4:将A类在B类中实例化来实现组合关系

      

      代码实现:

     1 public class A {
     2     void operation1() {
     3         //do something...
     4     }
     5 
     6     void operation2() {
     7         //do something...
     8     }
     9 }
    10 
    11 class B {
    12     A a = new A();
    13 }

    三、设计原则的核心思想

      (1)找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起

      (2)针对接口编程,而不是针对实现编程

      (3)为了交互对象之间的松耦合设计而努力

  • 相关阅读:
    程序员常见的坏习惯,你躺枪了吗?
    程序员常见的坏习惯,你躺枪了吗?
    程序员常见的坏习惯,你躺枪了吗?
    ACM2037
    [Golang]字符串拼接方式的性能分析
    如果一个类同时继承的两个类都定义了某一个函数会怎样呢 | Code4Fun
    Python学习笔记(四)函数式编程
    MySql之增删改查 · YbWork's Studio
    季銮西的博客
    ActiveMQ学习总结(一)
  • 原文地址:https://www.cnblogs.com/yijiahao/p/14502519.html
Copyright © 2011-2022 走看看