设计模式|七大原则及案例分析

设计模式

设计模式(design pattern)是对软件设计模式中普遍存在的各种问题所提出的解决方案。是从建筑设计领域引入到计算机科学的。

目的

  1. 代码重用性:相同功能的代码,不用多次编写

  2. 可读性:编程规范性,便于其他程序员的阅读和理解

  3. 可扩展性:需要新增功能时非常方便,也称为可维护性

  4. 可靠性:新增的佳能对原来的功能不会造成影响

  5. 高内聚、低耦合:模块内部紧密,模块之间隔离

七大原则

设计模式原则,其实就是程序员在编程时,应当遵守的原则,也是各种设计模式的基础(即:设计模式为什么这样设计的依据)

  1. 单一职责原则

  2. 接口隔离原则

  3. 依赖倒转(倒置)原则

  4. 里氏替换原则

  5. 开闭原则 ocp

  6. 迪米特原则

  7. 合成服用原则

单一职责原则

用一句话来说就是:一个类应该只负责一项职责

示例

/*
 * 单一职责模式Demo
 */
public class SimpleResponsibility1 {
	public static void main(String[] args) {
		Vehicle vehicle = new Vehicle();
		vehicle.run("摩托车");
		vehicle.run("汽车");
		vehicle.run("飞机");
		vehicle.run("轮船");
	}
}
// 交通工具 
class Vehicle{
	// 跑的方法
	public void run(String vehicle) {
		System.out.println(vehicle+" 在公共路上运行...");
	}
}

结果

摩托车 在公共路上运行...
汽车 在公共路上运行...
飞机 在公共路上运行...
轮船 在公共路上运行...

从输入结果来看显然是不对的,需要对 Vehicle 类进行修改

改进1

public class SimpleResponsibility2 {
	public static void main(String[] args) {
		RunVehicle runVehicle = new RunVehicle();
		runVehicle.run("摩托车");
		runVehicle.run("汽车");
		AirVehicle airVehicle = new AirVehicle();
		airVehicle.run("飞机");
		WaiterVehicle waiterVehicle = new WaiterVehicle();
		waiterVehicle.run("轮船");
	}
}
//公路交通工具 
class RunVehicle{
	public void run(String vehicle) {
		System.out.println(vehicle+" 在公共路上运行...");
	}
}
//飞行交通工具 
class AirVehicle{
	public void run(String vehicle) {
		System.out.println(vehicle+" 在天上运行...");
	}
}
//水路交通工具 
class WaiterVehicle{
	public void run(String vehicle) {
		System.out.println(vehicle+" 在水中运行...");
	}
}

结果

摩托车 在公共路上运行...
汽车 在公共路上运行...
飞机 在天上运行...
轮船 在水中运行...

输入的结果是正确的,也符合单一指责模式,但是对于这种需求的话还是有点问题,改动太大,将类分解,同时需要修改客户端。

改进2

public class SimpleResponsibility3 {
	public static void main(String[] args) {
		Vehicle2 vehicle2 = new Vehicle2();
		vehicle2.runRoad("摩托车");
		vehicle2.runRoad("汽车");
		vehicle2.runAir("飞机");
		vehicle2.runWaiter("轮船");
	}
}

class Vehicle2 {
	public void runRoad(String vehicle) {
		System.out.println(vehicle+" 在公共路上运行...");
	}
	public void runAir(String vehicle) {
		System.out.println(vehicle+" 在天上运行...");
	}
	public void runWaiter(String vehicle) {
		System.out.println(vehicle+" 在水中运行...");
	}
}

结果

摩托车 在公共路上运行...
汽车 在公共路上运行...
飞机 在天上运行...
轮船 在水中运行...

结果同样是正确的,这样做的好处就是没有对原来的类进行大的修改,只是增加了方法,虽然在类的级别没有符合单一职责原则,但是在方法的级别符合单一职责原则

注意事项

  1. 降低类的负责度,一个类只负责一项原则

  2. 提高类的可读性、可维护性

  3. 降低变更带来的风险

  4. 通常情况下,我们应该遵守单一职责原则,只有逻辑足够简单,才可以在代码级违反单一职责原则:只有类中的方法数量足够少,可以在方法级别保持单一职责原则。

接口隔离原则

接口隔离原则(Interface Segregation Principle),客户端不应该依赖它不需要的接 口,即一个类对另一个类的依赖 应该建立在最小的接口上

示例

public class Segregation1{

}
//接口
interface Interface1{
	void operation1();
	void operation2();
	void operation3();
}

class B implements Interface1{
	@Override
	public void operation1() {
		System.out.println("B 实现了 operation1");
	}
	@Override
	public void operation2() {
		System.out.println("B 实现了 operation2");
	}
	@Override
	public void operation3() {
		System.out.println("B 实现了 operation3");
	}
}

class D implements Interface1{
	@Override
	public void operation1() {
		System.out.println("D 实现了 operation1");
	}
	@Override
	public void operation2() {
		System.out.println("D 实现了 operation2");
	}
	@Override
	public void operation3() {
		System.out.println("D 实现了 operation3");
	}
}
class A{
	public void depend1(Interface1 i) {
		i.operation1();
	}
	public void depend2(Interface1 i) {
		i.operation2();
	}
}
class C{
	public void depend1(Interface1 i) {
		i.operation1();
	}
	public void depend3(Interface1 i) {
		i.operation3();
	}
}

通过分析 UML 图,我们可以发现A类只依赖于B类的1,3方法,同时C类只依赖于D类的2,3方法,但是B类和C类都把Interface1中的1,2,3方法都实现了,如果接口Interface1对于类A和类C来说不是最小接口,那么类B和类D必须去实现他们不需要的方法。

根据接口隔离原则,应该将Interface1接口拆分成三个接口,类A和类C分别与他们需要接口建立依赖关系。

改进

/*
 * 接口隔离原则Demo
 */
public class Segregation2{
	public static void main(String[] args) {
		A a = new A();
		a.depend1(new B());
		a.depend2(new B());
		
		C c = new C();
		c.depend1(new D());
		c.depend3(new D());
	}
}
//接口1
interface Interface1{
	void operation1();
}
//接口2
interface Interface2{
	void operation2();
}
//接口3
interface Interface3{
	void operation3();
}

class B implements Interface1,Interface2{
	@Override
	public void operation1() {
		System.out.println("B 实现了 operation1");
	}
	@Override
	public void operation2() {
		System.out.println("B 实现了 operation2");
	}
}

class D implements Interface1,Interface3{
	@Override
	public void operation1() {
		System.out.println("D 实现了 operation1");
	}
	@Override
	public void operation3() {
		System.out.println("D 实现了 operation3");
	}
}
class A{
	public void depend1(Interface1 i) {
		i.operation1();
	}
	public void depend2(Interface2 i) {
		i.operation2();
	}
}
class C{
	public void depend1(Interface1 i) {
		i.operation1();
	}
	public void depend3(Interface3 i) {
		i.operation3();
	}
}

结果

B 实现了 operation1
B 实现了 operation2
D 实现了 operation1
D 实现了 operation3

依赖倒转原则

依赖倒转原则(Dependence Inversion Principle)是指:

  1. 高层模块不应该 依赖低层模块,二者都应该依赖其抽象

  2. 抽象不应该依赖细节,细节应该依赖抽象

  3. 依赖倒转(倒置)的中心 思想是面向接口编程

  4. 依赖倒转原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在java中,抽象指的是接口或抽象类,细节就是具体的实现类

  5. 使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成

示例

public class DependecyInversion1 {
	public static void main(String[] args) {
		Person person = new Person();
		person.receive(new Email());
	}
}

class Email{
	public String getInfo() {
		return "电子邮件信息:你好";
	}
}

// Person 接受消息的功能
class Person{
	public void receive(Email email) {
		System.out.println(email.getInfo());
	}
}

结果

电子邮件信息:你好

从功能角度来看是完全没有问题的,但是现在如果加需求Person可以接受微信消息,那么他的弊端就体现出来了,需要新增Person类的接受方法。

解决思路:引入一个抽象的接口Receiver,表示接收者,这样Person类与接口Receiver发生依赖因为Email, WeiXin等等属于接收的范围,他们各自实现Receiver接口就行了,这样我们就符号依赖倒转原则

改进

public class DependecyInversion2 {
	public static void main(String[] args) {
		Person person = new Person();
		person.receive(new Email());
		person.receive(new WeiXin());
	}
}

//定义接口,接受消息
interface Receiver{
	public String getInfo();
}

class Email implements Receiver{
	@Override
	public String getInfo() {
		return "电子邮件信息:你好";
	}
}

class WeiXin implements Receiver{
	@Override
	public String getInfo() {
		return "微信信息:你好";
	}
	
}

// Person 接受消息的功能
class Person{
	public void receive(Receiver receiver) {
		System.out.println(receiver.getInfo());
	}
}

结果

电子邮件信息:你好
微信信息:你好

依赖关系传递的三种方式

  1. 接口传递

  2. 构造方法传递

  3. setter方法传递

注意事项和细节

  1. 低层模块尽量都要有抽象类或接口,或者两者都有,程序稳定性更好

  2. 变量的声明类型尽量是抽象类或接口,这样我们的变量引用和实际对象间,就存在一个缓冲层,利于程序扩展和优化

  3. 继承时遵循里氏替换原则

里氏替换原则

引言

  1. 继承包含这样-层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契约,虽然它不强制要求所有的子类必须遵循这些契约,但是如果子类对这些已经实现的方法任意修改,就会对整个继承体系造成破坏。

  2. 继承在给程序 设计带来便利的同时,也带来了弊端。比如使用继承会给程序带来侵入性,程序的可移植性降低,增加对象间的耦合性,如果- -个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且 父类修改后,所有涉及到子类的功能都有可能产生故障

  3. 问题提出:在编程中,如何正确的使用继承?=>里氏替换原则

基本介绍

  1. 里氏替换原则(Liskov Substitution Principle)在1988年,由麻省理工学院的以为姓里的女士提出的。

  2. 如果对每个类型为T1的对象o1,都有类型为T2的对象o2,使得以T1定义的所有程序P在所有的对象o1都代换成o2时,程序P的行为没有发生变化,那么类型T2是类型T1的子类型。换句话说,所有引用基类的地方必须能透明地使用其子类的对象。

  3. 在使用继承时, 遵循里氏替换原则,在子类中尽量不要重写父类的方法

  4. 里氏替换原则告诉我们, 继承实际上让两个类耦合性增强了,在适当的情况下,可以通过聚合,组合,依赖来解决问题

示例

public class Listiv {
	public static void main(String[] args) {
		A a = new A();
		System.out.println("12-2=" + a.func1(11, 3));
		System.out.println("2-6=" + a.func1(2, 6));
		
		B b = new B();
		System.out.println("12-2=" + b.func1(11, 3));
		System.out.println("2-6=" + b.func1(2, 6));
		
	}
}

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;
	}
}

结果

12-2=8
2-6=-4
12-2=14
2-6=8

观察结果我们可以发现结果是不正确的,因为B类误写了A类的一个方法,导致结果错误。

所以我们让A、B两个类集成一个基类,降低他们的耦合度,如果B类仍然想使用A类的方法可以使用聚合,组合,依赖来解决

改进

public class Listiv {
	public static void main(String[] args) {
		A a = new A();
		System.out.println("12-2=" + a.func1(11, 3));
		System.out.println("2-6=" + a.func1(2, 6));
		
		B b = new B();
		System.out.println("12+2=" + b.func1(11, 3));
		System.out.println("2+6=" + b.func1(2, 6));
		System.out.println("2+6+9=" + b.func2(2, 6));
		//仍然使用A类的方法
		System.out.println("2-8=" + b.func3(2, 8));
		
	}
}
// 基类
class Base {
	
}

class A extends Base{
	public int func1(int num1, int num2) {
		return num1 - num2;
	}
}
// 如果B类需要使用A类的功能,可以使用组合方式,降低耦合度
class B extends Base {
	// 组合A对象
	private A a = new A();
	public int func1(int a, int b) {
		return a + b;
	}
	
	public int func2(int a, int b) {
		return func1(a, b) + 9;
	}
	
	public int func3(int a, int b) {
		return this.a.func1(a, b);
	}
}

结果

12-2=8
2-6=-4
12+2=14
2+6=8
2+6+9=17
2-8=-6

开闭原则

  1. 开闭原则(Open Closed Principle)是编程中最基础、最重要的设计原则

  2. 一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现扩展细节。

  3. 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。

  4. 编程中遵循其它原则, 以及使用设计模式的目的就是遵循开闭原则。.

示例

public class OCP {
	public static void main(String[] args) {
		GraphicEditor graphicEditor = new GraphicEditor();
		graphicEditor.drawRectangle(new Reactagle());
		graphicEditor.drawCircle(new Circle());
	}
}

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 c) {
		System.out.println("绘制圆形");
	}
}
// 基类,图形类
class Shape {
	int m_type;
}
// 矩形类
class Reactagle extends Shape {
	public Reactagle() {
		super.m_type = 1;
	}
}
// 圆形类
class Circle extends Shape {
	public Circle() {
		super.m_type = 2;
	}
}

结果

绘制矩形
绘制圆形

结果是没有什么问题的,但是此时我们有了新的需求画三角形,于是我们需要新增三角形类,修改GraphicEditor类的方法,戏赠画三角的方法,违反了开闭原则。

改进

public class OCP {
	public static void main(String[] args) {
		GraphicEditor graphicEditor = new GraphicEditor();
		graphicEditor.drawShape(new Reactagle());
		graphicEditor.drawShape(new Circle());
		graphicEditor.drawShape(new Triangle());
	}
}

class GraphicEditor {
	public void drawShape(Shape s) {
		s.draw();
	}
}

// 基类,改为抽象,提供
abstract class Shape {
	int m_type;
	
	abstract void draw();
}
// 矩形类
class Reactagle extends Shape {
	public Reactagle() {
		super.m_type = 1;
	}

	@Override
	void draw() {
		System.out.println("绘制矩形");
	}
}
// 圆形类
class Circle extends Shape {
	public Circle() {
		super.m_type = 2;
	}

	@Override
	void draw() {
		System.out.println("绘制圆形");
	}
}
// 三角形类
class Triangle extends Shape{
	public Triangle() {
		super.m_type = 3;
	}

	@Override
	void draw() {
		System.out.println("绘制三角形");
	}
}

结果

绘制矩形
绘制圆形
绘制三角形

迪米特法则

  1. 一个对象应该对其他对象保持最少的了解

  2. 类与类关系越密切, 耦合度越大

  3. 迪米特法则(Demeter Principle)又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部。对外除了提供的public方法,不对外泄露任何信息

  4. 迪米特法则还有个更简单的定义:只与直接的朋友通信

    直接的朋友: 每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。耦合的方式很多,依赖,关联,组合,聚合等。其中,我们称出现成员变量,方法参数,方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的内部。

示例

public class Demeter {

	public static void main(String[] args) {
		//创建了一个 SchoolManager 对象
		SchoolManager schoolManager = new SchoolManager();
		//输出学院的员工id 和  学校总部的员工信息
		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 id;
	}
}

//管理学院员工的管理类
class CollegeManager {
	//返回学院的所有员工
	public List<CollegeEmployee> getAllEmployee() {
		List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
		for (int i = 0; i < 10; i++) { //这里我们增加了10个员工到 list
			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++) { //这里我们增加了5个员工到 list
			Employee emp = new Employee();
			emp.setId("学校总部员工id= " + i);
			list.add(emp);
		}
		return list;
	}

	//该方法完成输出学校总部和学院员工信息(id)
	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());
		}
	}
}

分析

 SchoolManager 类的直接朋友类有哪些 Employee、CollegeManager。CollegeEmployee不是 直接朋友而是一个陌生类,这样违背了 迪米特法则。

改进

public class Demeter1 {
	public static void main(String[] args) {
		//创建了一个 SchoolManager 对象
		SchoolManager schoolManager = new SchoolManager();
		//输出学院的员工id 和  学校总部的员工信息
		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 id;
	}
}

//管理学院员工的管理类
class CollegeManager {
	//返回学院的所有员工
	public List<CollegeEmployee> getAllEmployee() {
		List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
		for (int i = 0; i < 10; i++) { //这里我们增加了10个员工到 list
			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;
	}

	//该方法完成输出学校总部和学院员工信息(id)
	void printAllEmployee(CollegeManager sub) {
		
		sub.printEmployee();
	
		//获取到学校总部员工
		List<Employee> list2 = this.getAllEmployee();
		System.out.println("------------学校总部员工------------");
		for (Employee e : list2) {
			System.out.println(e.getId());
		}
	}
}

于是我们将输出学院的员工方法,封装到CollegeManager,只需要调用一下就可以了,符合迪米特原则。

注意事项和细节

  1. 迪米特法则的核心是降低类之间的耦合

  2. 但是注意:由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间(对象间)耦合关系,并不是要求完全没有依赖关系

合成复用原则

合成复用原则(Composite Reuse Principle),原则是尽量使用合成/聚合的方式,而不是使用继承。

核心思想

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

  2. 针对接口编程, 而不是针对实现编程。

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

发布了80 篇原创文章 · 获赞 55 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/cong____cong/article/details/104684450
今日推荐