caizhiyuannn.github.io

nothing to say.. @caizhiyuannn@gmail.com

View the Project on GitHub

Table of Contents

  1. 设计原则
    1. 单一职责
    2. 里氏替换原则
      1. 示例
    3. 依赖倒置原则
      1. 依赖的三种写法
    4. 接口隔离原则
    5. 迪米特法则
    6. 开闭原则

设计原则

资料:《设计模式模式之禅》


DONE 单一职责

单一职责原则,英文缩写SRP,全称Single Responsibility Principle。
原始定义:

There should never be more than one reason for a class to change。

DONE 里氏替换原则

原始定义:

  1. If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.
    如果对每一个类型为 T1的对象 o1,都有类型为 T2 的对象o2,使得以 T1定义的所有程序 P 在所有的对象 o1 都代换成 o2 时,程序 P 的行为没有发生变化,那么类型 T2 是类型 T1 的子类型。

  2. Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
    所有引用基类的地方必须能透明地使用其子类的对象。

遵循规则:

示例

// 抽象类
public abstract AbstractGun {
    public abstract void shoot();
}

// 子类实现父类或抽象类方法, 复写抽象类方法
class Handgun extends AbstractGun {
    @Override
    public void shoot() {
        System.out.println("Handgun");
    }
}

class Rifle extends AbstractGun {
    public void shoot() {
        System.out.println("Rifle");
    }
}

// 调用
class  Soldier {
    private AbstractGun gun;

    public void setGun(AbstractGun _gun) {
        this.gun = _gun
    }

    public void killEnemy() {
        this.gun.shoot();
    }
}

//
public class Client {
    public static void main(String[], args) {
        Soldier sanmao = new Soldier();
        sanmao.setGun(new Rifle);
        sanmao.killEnemy();
    }
}

DONE 依赖倒置原则

原始定义:

High level modules should not depend upon low level modules. Both should depend upon abstractions.
Abstractions should not depend upon details. Details should depend upon abstractions.

依赖的三种写法

    // 依赖 ICar 接口实现的car
    
    public interface IDriver {
        public void drive();
    }
    
    public class Driver implements IDriver {
        private ICar car;
        // 通过构造函数注入依赖的对象
        public Driver(Icar _car) {
            this.car = _car;
        }
    
        public void drive() {
            this.car.run();
        }
    
    }
    
    // 依赖ICar 接口实现的car
    
    public interface IDriver {
        public void setCar(Icar car);
        public void drive();
    
    }
    
    public class Driver implements IDriver {
        private Icar car;
        public void setCar(Icar car) {
            this.car = car;
        }
    
        public void drive() {
            this.car.run();
        }
    }
    
    // 通过接口声明依赖对象
    
    public interface IDriver {
        public void drive(ICar car);
    }
    
    
    public class Driver implements IDriver {
        public void drive(ICar car) {
            car.run();
        }
    }
    

TODO 接口隔离原则

TODO 迪米特法则

TODO 开闭原则