设计模式基本介绍

设计模式

23种设计模式
编写软件过程中, 程序员面临着来自 耦合性, 内聚性以及可维护性, 可扩展性, 重用性, 灵活性 等多方面的挑战, 设计模式是为了让程序(软件), 具有更好的

  1. 代码重用性(相同功能的代码, 不用多次编写)
  2. 可读性(编程规范性, 便于其他人阅读理解)
  3. 可扩展性
  4. 可靠性(新增功能后, 对原有功能没有影响)
  5. 使程序呈现高内聚, 低耦合的特性
    模块内部是非常紧密的, 功能和功能之间是低耦合的

设计模式包含了大量的编程思想

设计模式七大原则

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

七大原则
  1. 单一职责原则
  2. 接口隔离原则
  3. 依赖倒转(倒置)原则
  4. 里氏替换原则
  5. 开闭原则
  6. 迪米特法则
  7. 合成复用原则

单一职责原则(Single responsibility principle, SRP)

对类来说, 即一个类应该只负责一项职责, 如果类A负责两个不同职责: 职责1、职责2 . 当职责1需求变更而改变A时, 可能造成职责2 执行错误, 所以需要将类A的粒度分解为A1、A2.
方法1:

public class SingleResponsibility1 {
	//单一职责原则
	public static void main(String[] args) {
		Vehicle v = new Vehicle();
		v.run("摩托");
		v.run("汽车");
		v.run("飞机");
		
	}

}
//在方法1的run方法中,违反了单一职责原则
class Vehicle{
	public void run(String vehicle) {
		System.out.println(vehicle+"在公路上跑");
	}
}

改进方法1

public class SingleResponsibility2 {
	public static void main(String[] args) {
		RoadVehicle r = new RoadVehicle();
		AirVehicle a = new  AirVehicle();
		WaterVehicle w = new WaterVehicle();
		r.run("摩托车");
		a.run("飞机");
		w.run("船");
		
	}
//遵守了单一职责原则, 但是这样做花销很大, 将类分解, 同时修改客户端
//改进
}
class RoadVehicle{
	public void run(String vihechle) {
		System.out.println(vihechle+"在公路运行");
	}
}
class AirVehicle{
	public void run(String vihechle) {
		System.out.println(vihechle+"在天空运行");
	}
}
class WaterVehicle{
	public void run(String vihechle) {
		System.out.println(vihechle+"在水路运行");
	}
}

再次更改

public class SingleResponsibility3 {
	public static void main(String[] args) {
		Vehicle v = new Vehicle();
		v.run("car");
		v.runAIR("plane");
		v.runWater("boat");
	}

}
//没有在类这个级别遵守单一职责原则, 但是在方法级别上,仍然是遵守单一职责

class Vehicle{
	public void run(String vehicle) {
		System.out.println(vehicle+"在公路上跑");
	}
	public void runAIR(String vehicle) {
		System.out.println(vehicle+"在空中上跑");
	}
	public void runWater(String vehicle) {
		System.out.println(vehicle+"在水路上跑");
	}
}

单一职责原则注意事项和细节

  1. 降低类的复杂度, 一个类只负责一项职责.
  2. 提高类的可读性, 可维护性
  3. 降低变更引起的风险
  4. 通常情况下, 我们应当遵守单一职责原则, 只有逻辑足够简单, 才可以在代码级违反单一职责原则, 只有类中方法数量足够多, 可以在方法级别保持单一职责原则

接口隔离原则(Interface Segregation Principle, ISP)

客户端不应该依赖它不需要的接口, 即一个类对另一个类的依赖应该建立在最小的接口上.
在这里插入图片描述
代码展示

	public interface I1 {
	void oper1();
	void oper2();
	void oper3();
	void oper4();
	void oper5();

}
class B implements I1{
	public void oper1() {
		System.out.println("oper1");
	}
	public void oper2() {
		System.out.println("oper2");
	}
	public void oper3() {
		System.out.println("oper3");
	}
	public void oper4() {
		System.out.println("oper4");
	}
	public void oper5() {
		System.out.println("oper5");
	}
}
class D implements I1{
	public void oper1() {
		System.out.println("oper1");
	}
	public void oper2() {
		System.out.println("oper2");
	}
	public void oper3() {
		System.out.println("oper3");
	}
	public void oper4() {
		System.out.println("oper4");
	}
	public void oper5() {
		System.out.println("oper5");
	}
}
class A{// A类通过接口I1 依赖(使用)B类, 但只会用到1,2,3方法
	public void depend1(I1 i) {
		i.oper1();
	}
	public void depend2(I1 i) {
		i.oper2();
	}
	public void depend3(I1 i) {
		i.oper3();
	}
}
class C{
	public void depend1(I1 i) {
		i.oper1();
	}
	public void depend3(I1 i) {
		i.oper4();
	}
	public void depend4(I1 i) {
		i.oper5();
	}
}

接口隔离原则注意事项和细节

类A通过接口 I1 依赖类B, 类C通过接口 I1依赖类D, 如果接口 I1对于类A和类C来说不是最小接口那么类B和类D必须去实现他们不需要的方法.
按隔离原则应当这样处理: 将接口 I1 拆分为独立的几个接口, 类A和类C分别于他们需要的接口建立依赖关系. 也就是采用接口隔离原则.
接口 I1中出现的方法, 根据实际情况拆分为三个接口
改进后的代码

public interface Interface1 {
	void oper1();
}
public interface Interface2 {
	void oper2();
	void oper3();
}
public interface Interface3 {
	void oper4();
	void oper5();
}
class B implements Interface1,Interface2{
	public void oper1() {
		System.out.println("oper1");
	}
	public void oper2() {
		System.out.println("oper2");
	}
	public void oper3() {
		System.out.println("oper3");
	}
}
class D implements Interface1,Interface3{
	public void oper1() {
		System.out.println("oper1");
	}
	public void oper4() {
		System.out.println("oper4");
	}
	public void oper5() {
		System.out.println("oper5");
	}
}
class A{
	public void depend1(Interface1 i) {
		i.oper1();
	}
	public void depend2(Interface2 i) {
		i.oper2();
	}
	public void depend3(Interface2 i) {
		i.oper3();
	}
}
class C{
	public void depend1(Interface1 i) {
		i.oper1();
	}
	public void depend4(Interface3 i) {
		i.oper4();
	}
	public void depend3(Interface3 i) {
		i.oper5();
	}
}

在这里插入图片描述

依赖倒转原则(Dependence Inversion Principle)

  1. 高层模块不应该依赖低层模块,二者都应该依赖其抽象
  2. 抽象不应该依赖细节,细节应该依赖抽象
  3. 依赖倒转(倒置)的中心思想是面向接口编程
  4. 依赖倒转原则是基于这样的设计理念: 相对于细节的多变性,抽象的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在java中,抽象指的是接口或抽象类,细节就是具体的实现类
  5. 使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成

代码展示

public class Inversion {

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

	}

}
class Email{
	public String getInfo() {
		return "电子邮件";
	}
}
//如果我们获取的对象是微信或短信等等, 则新增类, 同时person也要新增相应地接收方法
//解决思路: 引入一个抽象的接口Ireceiver, 表示接收者, 这样person类与接口Ireceiver发生依赖
//因为email ,微型等等属于接收的范围,他们各自实现Ireceiver 接口就没有问题, 这样我们就符合依赖倒转原则
class Person{
	public void receive(Email email){
		System.out.println(email.getInfo());
	}
}

改进代码

public class Inversion {

	public static void main(String[] args) {
		//客户端无需改变
		Person person = new Person();
		person.receive(new Email());
		person.receive(new Wechart());

	}

}
interface IReceiver{
	public String getInfo();
}
class Email implements IReceiver{
	public String getInfo() {
		return "电子邮件";
	}
}
class Wechart implements IReceiver{
	public String getInfo() {
		return "微信消息";
	}
}
class Person{
	public void receive(IReceiver recevier){
		System.out.println(recevier.getInfo());
	}
}

依赖的是接口

依赖关系传递的三种方式和应用案例

  1. 接口传递
//通过接口传递实现依赖
interface Iopenandclose{
	public void open(ITV tv);//抽象方法,接收接口
}
interface ITV{//ITV接口
	public void play();
}
//实现接口
class Openandclose implements Iopenandclose{
	public void open(ITV tv) {
		tv.play();
	}
}
  1. 构造方法传递
interface Iopenandclose{
	public void open();//抽象方法
}
interface ITV{//ITV接口
	public void play();
}
class Openandclose implements Iopenandclose{
	public ITV tv;	//成员
	public Openandclose(ITV tv) {//构造器
		this.tv = tv;
	}
	public void open() {
		this.tv.play();
	}
}
  1. setter方式传递
interface Iopenandclose{
	public void open();//抽象方法
	public void setTV(ITV tv);
}
interface ITV{//ITV接口
	public void play();
}
class Openandclose implements Iopenandclose{
	private ITV tv;
	public void setTV(ITV tv) {
		this.tv = tv;
	}
	public void open() {
		this.tv.play();
	}
}

实现类继承ITV接口即可, 三种方式的实现略有不同

class sanxing implements ITV{
	public void play() {
		System.out.println("三星");
	}
}
public static void main(String[] args) {
		sanxing sx = new sanxing();
		Openandclose o1 = new  Openandclose();//接口传递
		o1.open(sx);
		
		Openandclose o2 = new  Openandclose(sx);//构造方法传递
		o2.open();
		
		Openandclose o3 = new Openandclose();//set方法传递
		o3.setTV(sx);
		o3.open();
	}

依赖倒转原则注意事项

  1. 低层模块(低层不是底层)尽量都要有抽象类或接口, 或者两者都有, 程序稳定性更好.
  2. 变量的声明类型尽量是抽象类或接口, 这样我们的变量引用和实际对象间, 就存在一个缓冲层, 利于程序扩展和优化
  3. 继承时遵循里氏替换原则

里氏替换原则(Liskov Substitution Principle)

OO中的继承性的思考和说明 (OO面向对象(Object Oriented))

  1. 继承包含这样一层含义: 父类中凡是已经实现好的方法, 实际上是在设定规范和契约, 虽然它不强制要求所有子类必须遵循这些契约, 但是如果子类对这些已经实现的方法任意修改, 就会最整个继承体系造成破坏.
  2. 继承在给程序设计带来便利的同时, 也带来了弊端. 比如使用继承会给程序带来侵入性, 程序的可移植性降低, 增加对象间的耦合性, 如果一个类被其他的类所继承, 则当这个类需要修改时, 必须考虑到所有的子类, 并且父类修改后, 所有涉及到子类的功能都可能产生故障
  3. 在编程中,如何正确的使用继承 --> 里氏替换原则
里氏替换原则介绍:
  1. 如果对每个类型为T1的对象o1, 都有类型为T2的对象o2, 使得以T1定义的所有程序P在所有的对象o1都代换成o2时, 程序P的行为没有发生变化, 那么类型T2是类型T1的子类型。换句话说, 所有引用基类的地方必须能透明地使用其子类的对象。
  2. 在使用继承时, 遵循里氏替换原则, 在子类中尽量不要重写父类的方法
  3. 里氏替换原则告诉我们, 继承实际上让两个类耦合性增强了, 在适当的情况下,可以通过聚合, 组合, 依赖来解决问题

代码案例:
在这里插入图片描述

public class myun {
	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.println("11-3="+b.func1(11, 3));
		System.out.println("1-8="+b.func1(1, 8));
		System.out.println("11+3+9="+b.func2(11, 3));
	}
}
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;
	}
}

B类无意中重写了继承的A类方法
我们发现原来运行正常的相减功能发生了错误。原因就是类B无意中重写了父类的方法,造成原有功能出现错误。在实际编程中,我们常常会通过重写父类的方法完成新的功能,这样写起来虽然简单,但整个继承体系的复用性会比较差。特别是运行多态比较频繁的时侯.
通用的做法是:原来的父类和子类都继承一个更通俗的基类,原有的继承关系去掉,采用依赖,聚合,组合等关系代替

public class myun {
	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();
		//因为B类不再继承A类, 因此调用者不会再认为func1是减法
		//调用的功能就会明确
		System.out.println("11+3="+b.func1(11, 3));
		System.out.println("1+8="+b.func1(1, 8));
		System.out.println("11+3+9="+b.func2(11, 3));
		
		//使用A的方法
		System.out.println("11-3="+b.func3(11, 3));
	}
}
//创建一个更加基础的基础类
class Base{
	
}
class A extends Base{
	public int func1(int num1,int num2) {
		return num1-num2;
	}
}
class B extends Base{
	//如果B需要使用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;
	}
	//使用A的方法
	public int func3(int a,int b) {
		return this.a.func1(a, b);
	}
}

开闭原则(Open Closed Principle)

  1. 开闭原则是编程中最基础、最重要的设计原则.
  2. 一个软件实体如类, 模块和函数应该对扩展开放(对提供方), 对修改关闭(对适用方). 用抽象构建框架, 用实现扩展细节.
  3. 当软件需要变化时, 尽量通过扩展软件实体的行为来实现变化, 而不是通过修改已有的代码来实现变化.
  4. 编程中遵循其他原则, 以及使用设计模式的目的就是遵循开闭原则.

代码展示

public class myun {
	public static void main(String[] args) {
		GraphicEditor g = new GraphicEditor();
		g.drawCircle(new Circle());
		g.drawRectangle(new Rectangle());
	}
}
//这是一个用于绘图的类
class GraphicEditor{
	//接收shape对象,根据type来绘制不同的图形
	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{
	public Rectangle(){
		super.m_type = 1;
	}
}
class Circle extends Shape{
	 public  Circle() {
		super.m_type = 2;
	}
}

这样编写的代码优点是比较好理解, 简单易操作; 缺点是违反了设计模式的ocp原则, 即对扩展开放(提供方), 对修改关闭(适用方). 即当我们给类增加新功能的时候, 尽量不修改代码, 或者尽可能少修改代码.
现在要在原有基础上新增一个图形种类

public class myun {
	public static void main(String[] args) {
		GraphicEditor g = new GraphicEditor();
		g.drawCircle(new Circle());
		g.drawRectangle(new Rectangle());
		g.drawTriangle(new Triangle());
	}
}
//这是一个用于绘图的类
class GraphicEditor{
	//接收shape对象,根据type来绘制不同的图形
	public void drawShape(Shape s) {
		if(s.m_type==1) {
			drawRectangle(s);
		}
		else if(s.m_type==2)
			drawCircle(s);
		else if(s.m_type==3)
			drawTriangle(s);
	}
	public void drawRectangle(Shape r) {
		System.out.println("矩形");
	}
	public void drawCircle(Shape r) {
		System.out.println("圆形");
	}
	public void drawTriangle(Shape r) {
		System.out.println("三角形");
	}
}
class Shape{
	int m_type;
}
class Rectangle extends Shape{
	public Rectangle(){
		super.m_type = 1;
	}
}
class Circle extends Shape{
	 public  Circle() {
		super.m_type = 2;
	}
}
class Triangle extends Shape{
	public Triangle() {
		super.m_type = 3;
	}
}

违背了OCP原则

对以上代码的改进思路
把创建的shape类做成抽象类, 并提供一个抽象的draw方法, 让子类去实现即可. 这样我们有新的图形种类时, 只需要让新的图形继承shape, 并实现draw方法即可, 适用方的代码就不需要修改, 这样才满足开闭原则

改进后的代码:

public class myun {
	public static void main(String[] args) {
		GraphicEditor g = new GraphicEditor();
		g.drawshape(new Rectangle());
		g.drawshape(new Circle());
		g.drawshape(new Triangle());
		g.drawshape(new Other());
		
	}
}
//这是一个用于绘图的类
class GraphicEditor{
	//接收shape对象,根据type来绘制不同的图形
	public void drawshape(Shape e) {
		e.draw();
	}
	
}
abstract class Shape{
	abstract void draw(); //抽象方法
}
class Rectangle extends Shape{
	public void draw() {
		System.out.println("矩形");
	}
}
class Circle extends Shape{
	public void draw() {
		System.out.println("圆形");
	}
}
class Triangle extends Shape{
	public void draw() {
		System.out.println("三角形");
	}
}
//新增其他图形
class Other extends Shape{
	public void draw() {
		System.out.println("其他图形");
	}
}

改进后的代码满足开闭原则.

迪米特法则(Demeter Principle)

  1. 一个对象应该对其他对象保持最少的了解
  2. 类与类关系越密切, 耦合度越大
  3. 迪米特法则( Demeter Principle)又叫最少知道原则, 即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂, 都尽量将逻辑封装在类的内部。对外除了提供的 public方法,不对外泄露任何信息.
  4. 迪米特法则还有个更简单的定义: 只与直接的朋友通信.

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

代码展示

import java.util.ArrayList;
import java.util.List;
public class Demeter {
	//有一个学校, 下属有各个学院和总部, 现要求打印出学校总部员工ID和学院员工的ID
	public static void main(String[] args) {
		SchoolManager sm = new SchoolManager();
		sm.printAllEmployee(new CollegeManager());
	}
}
//学校总部员工类
class Employee{
	private String id;
	public void setID(String id) {
		this.id = id;
	}
	public String getID() {
		return this.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++) { //增加是十个员工到list集合
			CollegeEmployee emp = new CollegeEmployee();
			emp.setID("学院员工id= "+i);
			list.add(emp);
		}
		return list;
	}
}
//学校管理类
//SchoolManager类的直接朋友有哪些: Employee CollegeManager
//CollegeEmployee不是直接朋友, 而是一个陌生类, 这样违背了迪米特法则
class SchoolManager{
	public List<Employee> getAllEmployee(){	//方法返回值中的类Employee
		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) { //方法参数CollegeManager
		List<CollegeEmployee> list1 = sub.getAllEmployee();
		//上一行的CollegeEmployee即不是成员变量,也不是方法参数
		//CollegeEmployee是以局部变量方式出现在schoolManager, 违反了迪米特法则
		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());
		}
	}
}

对以上代码进行改进, 应该避免非直接朋友关系的耦合

import java.util.ArrayList;
import java.util.List;
public class Demeter {
	//有一个学校, 下属有各个学院和总部, 现要求打印出学校总部员工ID和学院员工的ID
	public static void main(String[] args) {
		SchoolManager sm = new SchoolManager();
		sm.printAllEmployee(new CollegeManager());
	}
}

class Employee{
	private String id;
	public void setID(String id) {
		this.id = id;
	}
	public String getID() {
		return this.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;
	}
	//输出学院员工的信息
	public void printEmployee() {
		List<CollegeEmployee> list1 = this.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) { 
		//解决思路:将输出学院的方法封装到CollegeManager
		sub.printEmployee();
		List<Employee> list2 = this.getAllEmployee();
		System.out.println("学校总部员工-----");
		for(Employee e:list2) {
			System.out.println(e.getID());
		}
	}
}

将学院的输出封装到CollegeManager类中, 再又CollegeManager的引用调用即可, 其他程序都无需改变.

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

合成复用原则(Composite Reuse Principle)

原则是尽量使用合成/聚合的方式, 而不是使用继承

七大设计原则核心思想

  1. 找出应用中可能需要变化之处, 把他们独立出来, 不要和那些不需要变化的代码混在一起.
  2. 针对接口编程, 而不是针对实现编程.
  3. 为了交互对象之间松耦合设计而努力.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值