设计模式的作用
-
代码重用性
-
可读性
-
可扩展性
-
可靠性
-
使程序呈现高内聚,低耦合的特性
设计模式常用的七大原则有
-
单一职责原则
-
接口隔离原则
-
依赖倒转原则
-
里式替换原则
-
开闭原则OCP
-
迪米特法则
-
合成复用原则
单一职责原则
对类来说的,即一个应该只负责 项职。如类 A负责两个不同职 :责两个不同职 :责1,职 责2。 当职 责1需求变更而改 变A时,可能造成职 责2执行错误, 所以需要将 类A的粒度分解 为 A1,A2
public class single {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.run("摩托车!");
vehicle.run("汽车!");
vehicle.run("飞机!");
}
}
class Vehicle {
public void run(String vehicle) {
System.out.println(vehicle + "在公路上运行!");
}
}
飞机动作与摩托和汽车不符违反了单一原则
public class single2 {
@Test
public static void main(String[] args) {
RoadVehicle vehicle = new RoadVehicle();
vehicle.run("摩托车!");
vehicle.run("汽车!");
AirVehicle airVehicle = new AirVehicle();
airVehicle.run("飞机");
}
}
class RoadVehicle {
public void run(String vehicle) {
System.out.println(vehicle + "在公路上运行!");
}
}
class AirVehicle {
public void run(String vehicle) {
System.out.println(vehicle + "天空上运行!");
}
}
虽然遵守单一原则但浪费资源非常繁重
public class single3 {
@Test
public static void main(String[] args) {
Vehicle1 vehicle = new Vehicle1();
vehicle.run("摩托车!");
vehicle.run("汽车!");
vehicle.run2("飞机");
vehicle.run3("小船");
}
}
class Vehicle1 {
public void run(String vehicle) {
System.out.println(vehicle + "在公路上运行!");
}
public void run2(String vehicle) {
System.out.println(vehicle + "在天空上运行!");
}
public void run3(String vehicle) {
System.out.println(vehicle + "在水中翱翔!");
}
}
这种修改方法没有对原来的类做大的修改,只是增加方法,在类级别没有遵守单一原则,但在方法上遵守单一原则
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)