0、设计模式分类
创建型模式
用于描述”怎样创建对象”,它的主要特点是”将对象的创建与使用分离”。GoF(四人组)书中提供了单例、原型、工厂方法、抽象工厂、建造者等5种创建型模式。
结构型模式
用于描述如何将类或对象按某种布局组成更大的结构,GoF(四人组)书中提供了代理、适配器、桥接、装饰、外观、享元、组合等7种结构型模式。
行为型模式
用于描述类或对象之间怎样相互协作共同完成单个对象无法单独完成的任务,以及怎样分配职责。GoF(四人组)书中提供了模板方法、策略、命令、职责链、状态、观察者、中介者、迭代器、访问者、备忘录、解释器等11种行为型模式。
在软件开放中,为了提高软件系统的可维护性和可复用性,增加软件的可扩展性和灵活性,程序员要尽量根据7条原则来开发程序,从而提高软件开发效率、节约软件开发成本和维护成本。
1、单一职责原则
【1】基本介绍
对类来说的,即一个类应该只负责一项职责。如类A负责两个不同职责:职责1,职责2。当职责1需求变更而改变A时,可能造成职责2执行错误,所以需要将类A的粒度分解为A1,A2。
【2】以交通工具案例讲解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class Vehicle { public void run(String vehicle) { System.out.println(vehicle + " 在公路上行驶。。。"); } public static void main(String[] args) { Vehicle vehicle = new Vehicle(); vehicle.run("摩托车"); vehicle.run("汽车"); vehicle.run("飞机"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
class RoadVehicle { public void run(String vehicle) { System.out.println(vehicle + "公路运行"); } }
class AirVehicle { public void run(String vehicle) { System.out.println(vehicle + "天空运行"); } }
class WaterVehicle { public void run(String vehicle) { System.out.println(vehicle + "水中运行"); } }
class SingleResponsibility { RoadVehicle rv = new RoadVehicle(); rv.run(); AirVehicle av = new RoadVehicle(); av.run(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Vehicle { public void runRoad(String vehicle) { System.out.println(vehicle + "在公路上运行...") } public void runAir(String vehicle) { System.out.println(vehicle + "在天空上运行...") } public void runWater(String vehicle) { System.out.println(vehicle + "在水中运行...") } public static void main(String[] args) { Vehicle v = new Vehicle(); v.runRoad("汽车"); v.runWater("轮船"); v.runAir("飞机"); } }
|
【3】单一职责原则注意事项和细节
- 降低类的复杂度,一个类只负责一项职责。
- 提高类的可读性,可维护性。
- 降低变更引起的风险。
- 通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码级别违反单一职责原则;
只有类中方法数量足够少,可以在方法级别保持单一职责原则。
2、接口隔离原则
【1】基本介绍
客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上。

类A通过接口Interface1依赖类B,类C通过接口Interface1依赖类D,如果接口Interface1对于类A和类C来说不是最小接口,那么类B和类D必须去实现他们不需要的方法。
按隔离原则应当这样处理:将接口Interface1拆分为独立的几个接口,类A和类C分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则。
【2】代码展示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
interface Interface1 { void operation1(); void operation2(); void operation3(); void operation4(); void operation5(); }
class B implements Interface1 { public void operation1() { System.out.println("B 实现了 operation1"); } public void operation2() { System.out.println("B 实现了 operation2"); } public void operation3() { System.out.println("B 实现了 operation3"); } public void operation4() { System.out.println("B 实现了 operation4"); } public void operation5() { System.out.println("B 实现了 operation5"); } }
class D implements Interface1 { public void operation1() { System.out.println("D 实现了 operation1"); } public void operation2() { System.out.println("D 实现了 operation2"); } public void operation3() { System.out.println("D 实现了 operation3"); } public void operation4() { System.out.println("D 实现了 operation4"); } public void operation5() { System.out.println("D 实现了 operation5"); } }
class A { public void depend1(Interface1 i) { i.operation1(); } public void depend2(Interface1 i) { i.operation2(); } public void depend3(Interface1 i) { i.operation3(); } }
class C { public void depend1(Interface1 i) { i.operation1(); } public void depend4(Interface1 i) { i.operation4(); } public void depend5(Interface1 i) { i.operation5(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
interface Interface1 { void operation1(); }
interface Interface2 { void operation2(); void operation3(); }
interface Interface3 { void operation4(); void operation5(); }
class B implements Interface1, Interface2 { public void operation1() { System.out.println("B 实现了 operation1"); } public void operation2() { System.out.println("B 实现了 operation2"); } public void operation3() { System.out.println("B 实现了 operation3"); } }
class D implements Interface1, Interface3 { public void operation1() { System.out.println("D 实现了 operation1"); } public void operation4() { System.out.println("D 实现了 operation4"); } public void operation5() { System.out.println("D 实现了 operation5"); } }
class A { public void depend1(Interface1 i) { i.operation1(); } public void depend2(Interface2 i) { i.operation2(); } public void depend3(Interface2 i) { i.operation3(); } }
class C { public void depend1(Interface1 i) { i.operation1(); } public void depend4(Interface3 i) { i.operation4(); } public void depend5(Interface3 i) { i.operation5(); } }
public class Segregation { A a = new A(); a.depend1(new B()); a.depend2(new B()); a.depend3(new B()); C c = new C(); c.depend1(new D()); c.depend4(new D()); c.depend5(new D()); }
|
3、依赖倒转原则
【1】基本介绍
依赖倒转原则(Dependence Inversion Principle)是指:
1)高层模块不应该依赖低层模块,二者都应该依赖其抽象。
2)抽象不应该依赖细节,细节应该依赖抽象。
3)依赖倒转(倒置)的中心思想是面向接口编程。
4)依赖倒转原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在java中,抽象指的是接口或抽象类,细节就是具体的实现类。
5)使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成。
【2】代码展示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class Person { public void receive(Email email) { System.out.println(email.getInfo()); } }
class Email { public String getInfo() { return "电子邮件信息:hello,world"; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| interface IReceiver { String getInfo(); }
class Email implements IReceiver { public String getInfo() { return ""; } }
class WeiXin implements IReceiver { public String getInfo() { return ""; } }
class Person { public void receive(IReceiver rec) { System.out.println(rec.getInfo()); } }
|
依赖传递的三种方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
interface IOpenAndClose { void open(ITV tv); }
interface ITV { void play(); }
class OpenAndClose implements IOpenAndClose { public void open(ITV tv) { tv.play(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| interface IOpenAndClose { void open(); }
interface ITV { void play(); }
class OpenAndClose implements IOpenAndClose { public ITV tv; public OpenAndClose(ITV tv) { this.tv = tv; } public void open() { this.tv.play(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| interface IOpenAndClose { void open(); void setTv(ITV tv); }
interface ITV { void play(); }
class OpenAndClose implements IOpenAndClose { private ITV tv; public void setTv(ITV tv) { this.tv = tv; } public void open() { this.tv.play(); } }
|
【3】依赖倒转注意事项和细节
1)低层模块尽量都要有抽象类或接口,或者两者都有,程序稳定性更好。
2)变量的声明类型尽量是抽象类或接口,这样我们的变量引用和实际对象间,就存在一个缓冲层,利于程序扩展和优化。
3)继承时遵循里氏替换原则。
4、里氏替换原则
【1】OO中继承性的思考和说明
1)继承包含这样一层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契约,虽然它不强制要求所有的子类必须遵循这些契约,但是如果子类对这些已经实现的方法任意修改,就会对整个继承体系造成破坏。
2)继承在给程序设计带来便利的同时,也带来了弊端,比如使用继承会给程序带来侵入性,程序的可移植性降低,增加对象间的耦合性,如果一个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且父类修改后,所有涉及到子类的功能都可能产生故障。
3)问题提出:在编程中,如何正确的使用继承?=> 里氏替换原则
【2】基本介绍
1)里氏替换原则(Liskov Substitution Principle)在1988年,由麻省理工学院的一位姓里的女士提出的。
2)如果对每个类型为T1的对象o1,都有类型为T2的对象o2,使得以T1定义的所有程序P在所有的对象o1都代换成o2时,程序P的行为没有发生变化,那么类型T2是类型T1的子类型。换句话说,所有引用基类的地方必须能透明地使用其子类的对象。通俗来讲:任何基类可以出现的地方,子类一定可以出现。即子类可以扩展父类的功能,但不能改变父类原有的功能。即子类继承父类时,除添加新的方法完成新增功能外,尽量不要重写父类的方法。 如果通过重写父类的方法来完成新的功能,这样写起来虽然简单,但是整个继承体系的可复用性会比较差,特别是运用多态比较频繁时,程序运行出错的概率会非常大。
3)在使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类的方法。
4)里氏替换原则告诉我们,继承实际上让两个类耦合性增强了,在适当的情况下,可以通过聚合,组合,依赖来解决问题。
【3】思考代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class A { public int func1(int num1, int num2) { return num1 - num2; } }
class B extends A { public int func1(int a, int b) { return a + b; } public int func2(int a, int b) { return func1(a, b) + 9; } }
class Test { public static void main(String[] args) { A a = new A(); System.out.println("11-3=" + a.func1(11, 3)); System.out.println("1-8=" + a.func1(1, 8)); System.out.println("-----------------------"); B b = new B(); System.out.prinln("11-3=" + b.func1(11, 3)); System.out.prinln("1-8=" + b.func1(1, 8)); System.out.prinln("11+3+9=" + b.func2(11, 3)); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class Base { }
class A extends Base { public int func1(int num1, int num2) { return num1 - num2; } }
class B extends Base { private A a = new A(); public int func3(int a, int b) { return this.a.func1(a, b); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
public class Rectangle { private double length; private double width; public void setLength(double length) { this.length = length; } public double getLength() { return length; } public void setWidth(double width) { this.width = width; } public double getWidth() { return width; } }
public class Square extends Rectangle { @Override public void setLenth(double length) { super.setLength(length); super.setWidth(length); } @Override public void setWidth(double width) { super.setLength(width); super.setWidth(width); } }
public class RectangleDemo { public static void resize(Rectangle rectangle) { while(rectangle.getWidth() <= rectangle.getLenth()) { rectangle.setWidth(rectangle.getWidth() + 1); } } public void printLengthAndWidth(Rectangle rectangle) { System.out.println(rectangle.getLenth()); System.out.println(rectangle.getWidth()); } public static void main(String[] args) { Rectangle r = new Rectangle(); r.setWidth(10); r.setLength(20); resize(r); printLengthAndWidth(r); Square s = new Square(); s.setLenth(10); resize(s); printLengthAndWidth(s); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
public interface Quadrilateral { double getLength(); double getWidth(); }
public class Rectangle implements Quadrilateral { private double length; private double width; public void setLength(double length) { this.length = length; } public double getLength() { return length; } public void setWidth(double width) { this.width = width; } public double getWidth() { return width; } }
public class Square implements Quadrilateral { private double side; public void setSide(double side) { this.side = side; } public double getSide() { return side; } public double getLength() { return side; } public double getWidth() { return side; } }
public class RectangleDemo { public static void resize(Rectangle rectangle) { while(rectangle.getWidth() <= rectangle.getLenth()) { rectangle.setWidth(rectangle.getWidth() + 1); } } public void printLengthAndWidth(Quadrilateral quadrilateral) { System.out.println(quadrilateral.getLenth()); System.out.println(quadrilateral.getWidth()); } public static void main(String[] args) { Rectangle r = new Rectangle(); r.setWidth(10); r.setLength(20); resize(r); printLengthAndWidth(r); Square s = new Square(); s.setLenth(10); printLengthAndWidth(s); } }
|
5、开闭原则
【1】基本介绍
1)开闭原则(Open Closed Principle)是编程中最基础、最重要的设计原则。
2)一个软件实体如类,模块和函数应该对扩展开放,对修改关闭。用抽象构建框架,用实现扩展细节。
3)当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
4)编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则。
要想达到这样的效果,我们需要使用接口和抽象类。
因为抽象灵活性好,适应性广,只要抽象的合理,可以基本保持软件架构的稳定。而软件中易变的细节可以从抽象派生来的实现类来进行扩展,当软件需要发生变化时,只需要根据需求重新派生一个实现类来扩展就可以了。
【2】阅读代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
class GraphicEditor { public void drawShape(Shape s) { if(s.m_type == 1) { drawRectangle(s); }else if(s.m_type == 2) { drawCircle(s); } } public void drawRectangle(Shape r) { System.out.println("矩形"); } public void drawCircle(Shape r) { System.out.println("圆形"); } }
class Shape { int m_type; }
class Rectangle extends Shape { Rectangle() { super.m_type = 1; } }
class Circle extends Shape { Circle() { super.m_type = 2; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
abstract class Shape { public abstract void drawShape(); }
class Rectangle extends Shape { public void drawShape(){ System.out.println("长方形"); } }
class Circle extends Shape { public void drawShape(){ System.out.println("圆形"); } }
class GraphicEditor { public void drawShape(Shape shape) { shape.drawShape(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
public abstract class AbstractSkin { public abstract void display(); }
public class DefaultSpecificSkin extends AbstractSkin { public void display() { System.out.println("默认皮肤"); } }
public class HeimaSpecificSkin extends AbstractSkin { public void display() { System.out.println("黑马皮肤"); } }
public class SouGouInput { private AbstractSkin skin; public SouGouInput(AbstractSkin skin) { this.skin = skin; } public void display() { skin.display(); } }
|
6、迪米特法则
【1】基本介绍
1)一个对象应该对其他对象保持最少的了解。
2)类与类关系越密切,耦合度越大。
3)迪米特法则(Demeter Principle)又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部。对外除了提供的public方法,不对外泄漏任何信息。
4)迪米特法则还有个更简单的定义:只与直接的朋友通信。
5)直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。耦合的方式很多,依赖,关联,组合,聚合等。其中,我们称成员变量、方法参数、方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的内部。
【2】代码案例
1)有一个学校,下属有各个学院和总部,现在要求打印出学校总部员工ID和学院员工ID。
2)编程实现上面的功能,看代码演示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| public class Demeter { public static void main(String[] args) { SchoolManager schoolManager = new SchoolManager(); schoolManager.printAllEmployee(new CollegeManager()); } }
class Employee { private String id; public void setId(String id) { this.id = id; } public String getId() { return id; } }
class CollegeEmployee { private String id; public void setId(String id) { this.id = id; } public String getId() { return this.id; } }
class CollegeManager { public List<CollegeEmployee> getAllEmployee() { List<CollegeEmployee> list = new ArrayList<CollegeEmployee>(); for (int i = 0; i < 10; i++) { CollegeEmployee emp = new CollegeEmployee(); emp.setId("学院员工id=" + i); list.add(emp); } return list; } }
class SchoolManager { public List<Employee> getAllEmployee() { List<Employee> list = new ArrayList<Employee>(); for (int i = 0; i < 5; i++) { Employee emp = new Employee(); emp.setId("学校总部员工id=" + i); list.add(emp); } return list; } void printAllEmployee(CollegeManager sub) { List<CollegeEmployee> list1 = sub.getAllEmployee(); System.out.println("-------------分公司员工-------------"); for (CollegeEmployee e : list1) { System.out.println(e.getId()); } List<Employee> list2 = this.getAllEmployee(); System.out.println("-------------学校总部员工-------------"); for (Employee e : list2) { System.out.println(e.getId()); } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class CollegeManager { public List<CollegeEmployee> getAllEmployee() { List<CollegeEmployee> list = new ArrayList<CollegeEmployee>(); for (int i = 0; i < 10; i++) { CollegeEmployee emp = new CollegeEmployee(); emp.setId("学院员工id=" + i); list.add(emp); } return list; } public void printEmployee() { List<CollegeEmployee> list1 = getAllEmployee(); System.out.println("-------------学院员工-------------"); for (CollegeEmployee e : list1) { System.out.println(e.getId()); } } }
class SchoolManager { public List<Employee> getAllEmployee() { List<Employee> list = new ArrayList<Employee>(); for (int i = 0; i < 5; i++) { Employee emp = new Employee(); emp.setId("学校总部员工id=" + i); list.add(emp); } return list; } void printAllEmployee(CollegeManager sub) { sub.printEmployee(); List<Employee> list2 = this.getAllEmployee(); System.out.println("-------------学校总部员工-------------"); for (Employee e : list2) { System.out.println(e.getId()); } } }
|
【3】迪米特法则注意事项和细节
1)迪米特法则的核心是降低类之间的耦合。
2)但是注意:由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间(对象间)耦合关系,并不是要求完全没有依赖关系。
7、合成复用原则(Composite Reuse Principle)
【1】基本介绍
原则是尽量使用合成/聚合的方式,而不是使用继承。

【2】继承复用缺点和组合复用优点
1)继承复用破坏了类的封装性。因为继承会将父类的实现细节暴露给子类,父类对子类是透明的,所以这种复用又称为”白箱”复用。
2)子类与父类的耦合度高。父类的实现的任何改变都会导致子类的实现发生变化,这不利于类的扩展与维护。
3)它限制了复用的灵活性。从父类继承而来的实现是静态的,在编译时已经定义,所以在运行时不可能发生变化。
采用组合或聚合复用时,可以将已有对象纳入新对象中,使之称为新对象的一部分,新对象可以调用已有对象的功能,它有着以下优点:
1)它维持了类的封装性。因为成员对象的内部细节是新对象看不见的,所以这种复用又称为”黑箱”复用。
2)对象间的耦合度低。可以在类的成员位置声明抽象。
3)复用的灵活性高,这种复用可以在运行时动态进行,新对象可以动态地引用与成员对象类型相同的对象。(可传递该类或该成员的子类对象)
【3】汽车父类管理程序示例
汽车按”动力源”可划分为汽油汽车、电动汽车等。按”颜色”划分可分为白色汽车、黑色汽车和红色汽车等。如果同时考虑这两种分类,其组合就很多。类图如下:

从上面类图可以看到使用继承复用产生了很多子类,如果现在又有新的动力源或者新的颜色的话就需要定义新的类。试着改成聚合复用。

【4】设计原则核心思想
1)找出应用中可能需要变化之处,把他们独立出来,不要和那些不需要变化的代码混在一起。
2)针对接口编程,而不是针对实现编程。
3)为了交互对象之间的松耦合设计而努力。