nothing to say.. @caizhiyuannn@gmail.com
资料:《设计模式模式之禅》
单一职责原则,英文缩写SRP,全称Single Responsibility Principle。
原始定义:
There should never be more than one reason for a class to change。
原始定义:
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 的子类型。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();
}
}
原始定义:
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();
}
}