七大设计原则
七大设计原则是设计模式为什么这样设计的依据
单一职责原则
对于类来说,即一个类应该只负责一个职责,如类A负责两个不同的职责:职责1,职责2,当职责1需求发生变更而改变A时,可能造成职责2执行错误,所以需要将类A的颗粒度分解为A1,A2。即将A类分解成两个类A1,A2。
单一职责原则的注意事项和细节:
- 降低类的复杂度,一个类只负责一个职责;
- 提高类的可读性,可维护性
- 降低类变更时带来的风险
- 通常情况下,我们应当遵守单一职责原则,只有在逻辑足够简单,才能在代码级违反单一职责原则;只有类中方法数量足够少,可以在方法级别可以保持单一职责原则。
实例:
//违背单一职责原则
package com.luguangyou.principle.singleresponsibility;
public class Singleresponsibilityone {
public static void main(String[] args) {
Animal animal = new Animal();
animal.run("小鸡");
animal.run("小鸟");
animal.run("小鱼");
}
}
/*
从这个例子中我们看出这个animal违背了单一职责原则
因为小鸡可以在地上跑,但是小鸟是在天上飞的,小鱼是在水里游的
那么我们如何解决这个问题:
就要使用单一职责原则:一个类负责一个职责:即分别定义三个类
*/
class Animal{
public void run(String name){
System.out.println(name+"在地上跑");
}
}
package com.luguangyou.principle.singleresponsibility;
public class Singleresponsibilitytwo {
public static void main(String[] args) {
Chicken chicken = new Chicken();
chicken.run("小鸡");
Bird bird = new Bird();
bird.run("小鸟");
Fish fish = new Fish();
fish.run("小鱼");
}
}
/*
这个方式就解决了之前出现的代码变更产生的问题
但是这个这样的改动很大,即将类分解,也改动了客户端
改进:直接在类中编写多个方法,改动的代码比较少
*/
class Chicken{
public void run(String name){
System.out.println(name+"在陆地上跑");
}
}
class Bird{
public void run(String name){
System.out.println(name+"在天上飞");
}
}
class Fish{
public void run(String name){
System.out.println(name+"在水里游");
}
}
package com.luguangyou.principle.singleresponsibility;
public class Singleresponsibilitythree {
public static void main(String[] args) {
Animals animals = new Animals();
animals.ChickenRun("小鸡");
animals.BirdRun("小鸟");
animals.FishRun("小鱼");
}
}
class Animals{
public void ChickenRun(String name){
System.out.println(name+"在地上跑");
}
public void BirdRun(String name){
System.out.println(name+"在天上飞");
}
public void FishRun(String name){
System.out.println(name+"在水里游");
}
}
接口隔离原则
客户端不需要依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上。
比如类A和类C通过接口Interface去分别实现类B、类D的方法(即类A类C依赖类B类C),如果Interface不是类A类C的最小接口,那么类B和类D必须去实现他们不需要的方法
按接口隔离原则应该这样处理:将接口Interface拆分成独立的几个接口,类A和类C分别于他们需要的接口建立依赖关系,也就是采用接口隔离原则。
//不遵循接口隔离原则:
只有一个接口,类B、类D都实现这个接口,那么类B和类D都重写了自己不需要的方法。
package com.luguangyou.principle.segregation;
//遵循接口隔离原则
//类A通过接口Interface2、Interface3依赖类B
//类C通过接口Interface2、Interface4依赖类D
public class segregation2 {
public static void main(String[] args) {
A a = new A();
C c = new C();
a.depend1(new B());
a.depend2(new B());
a.depend3(new B());
c.depend1(new D());
c.depend4(new D());
c.depend5(new D());
}
}
interface Interface2{
public void operation1();
}
interface Interface3{
public void operation2();
public void operation3();
}
interface Interface4{
public void operation4();
public void operation5();
}
class B implements Interface2,Interface3{
@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 Interface2,Interface4{
@Override
public void operation1() {
System.out.println("D实现了operation1");
}
@Override
public void operation4() {
System.out.println("D实现了operation4");
}
@Override
public void operation5() {
System.out.println("D实现了operation5");
}
}
class A{
public void depend1(Interface2 i){
i.operation1();
}
public void depend2(Interface3 i){
i.operation2();
}
public void depend3(Interface3 i){
i.operation3();
}
}
class C{
public void depend1(Interface2 i){
i.operation1();
}
public void depend4(Interface4 i){
i.operation4();
}
public void depend5(Interface4 i){
i.operation5();
}
}
依赖倒转原则
- 高层模块不不应该依赖低层模块,他们都应该依赖于抽象
- 抽象不应该依赖于细节,细节应该依赖于抽象
- 依赖倒置的中心思想是面向接口编程
- 依赖倒置原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定得多,以抽象为基础搭建的架构比以细节为基础搭建的架构要稳定得多,在java中,抽象指的是抽象类或接口,细节就是具体的实现类。
- 使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成。
依赖倒置的三种传递方式(通过传递实现依赖):接口传递、构造器传递、setter方法传递
依赖倒置需要注意的3点:
- 低层模块尽量都要有抽象类或接口,或者两者都要有,程序的稳定性更好
- 变量的声明尽量是抽象类或接口,这样我们的变量和实际引用这件就存在一个缓冲层,利于程序扩展和优化。
- 继承时遵守里氏替换原则
//不符合依赖倒置原则
package com.luguangyou.principle.DependenceInversion;
public class DependenceInversion {
public static void main(String[] args) {
Email email = new Email();
Person person = new Person();
person.receive(email);
}
}
/*
方式一分析:
1.简单,比较容易想到
2.如果我们获取的对象是微信,短信等等,则新增类,同时Person也要增加相应的方法
3.解决思路:引入一个抽象的接口IReceiver,表示接收者,这样Person类与接口IReceiver发生依赖
因为微信和短信都是属于接收的范围,他们各自实现IReceiver接口就可以了,这样我们就符合依赖倒置原则
*/
class Email{
public String getInfo(){
return "你好,hello world";
}
}
class Person{
public void receive (Email email){
System.out.println(email.getInfo());
}
}
//符合依赖倒置原则
package com.luguangyou.principle.DependenceInversion;
public class improve {
public static void main(String[] args) {
//客户端不需要做改变
IReceiver receiver = new WeiXin();
Email1 receivers = new Email1();
Person1 person = new Person1();
person.receive(receivers);
}
}
//定义接口
interface IReceiver{
public String getInfo();
}
class Email1 implements IReceiver{
public String getInfo(){
return "你好,hello world";
}
}
//增加微信
class WeiXin implements IReceiver{
@Override
public String getInfo() {
return "我是微信服务器";
}
}
class Person1{
public void receive (IReceiver receive){
System.out.println(receive.getInfo());
}
}
依赖传递的三种方式
package com.luguangyou.principle.DependenceInversion;
public class DependencePass1 {
public static void main(String[] args) {
ChengHong chengHong = new ChengHong();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.open(chengHong);
}
}
/*
方式一:
通过接口传递实现依赖
*/
interface IOpenAndClose{
public void open(ITV tv);
}
interface ITV{
public String play();
}
//创建一个长虹类继承ITV
class ChengHong implements ITV{
@Override
public String play(){
return "长虹电视机";
}
}
//创建一个类继承IOpenAndClose
class OpenAndClose implements IOpenAndClose{
@Override
public void open(ITV tv) {
System.out.println("打开"+tv.play());
}
}
package com.luguangyou.principle.DependenceInversion;
public class DependencePass2 {
public static void main(String[] args) {
ChengHong1 chengHong1 = new ChengHong1();
OpenAndClose1 openAndClose = new OpenAndClose1(chengHong1);
openAndClose.open(chengHong1);
}
}
/*
方式2
通过构造方法传递依赖
*/
interface IOpenAndClose1{
public void open(ITV1 tv);
}
interface ITV1{
public String play();
}
class OpenAndClose1 implements IOpenAndClose1{
private ITV1 tv;
public OpenAndClose1(ITV1 tv){
this.tv = tv;
}
@Override
public void open(ITV1 tv) {
System.out.println("打开"+tv.play());
}
}
class ChengHong1 implements ITV1{
@Override
public String play(){
return "长虹电视机";
}
}
package com.luguangyou.principle.DependenceInversion;
public class DependencePass3 {
public static void main(String[] args) {
ChengHong2 chengHong2 = new ChengHong2();
OpenAndClose2 openAndClose2 = new OpenAndClose2();
openAndClose2.setTv(chengHong2);
openAndClose2.open();
}
}
/*
方式3:
通过setter方法传递
*/
interface IOpenAndClose2{
public void open();
public void setTv(ITV2 itv2);
}
interface ITV2{
public void play();
}
class OpenAndClose2 implements IOpenAndClose2{
private ITV2 itv2;
@Override
public void open() {
this.itv2.play();
}
@Override
public void setTv(ITV2 itv2) {
this.itv2 = itv2;
}
}
class ChengHong2 implements ITV2{
@Override
public void play() {
System.out.println("长虹电视打开");
}
}
里氏替换原则
oo中的继承性的思考和声明:
- 继承包含这样一层含义:父类凡是已经实现好的方法实际上是在设定规范和契约,虽然不强制要求所有子类都必须遵守这些契约,但是如果子类对这些已经实现了的方法任意的修改就会对整个继承体系造成破坏。
- 继承在给程序设计带来便利的同时也带来了弊端,比如使用继承会给程序带来侵入性,程序的可移植性降低,增加对象之间的耦合。
- 问题的提出:在编程中如果正确的使用继承==>里氏替换原则
里氏替换原则的基本介绍:
- 如果对每个类型为T1的对象o1都有类型T2的对象o2,使得以T1定义的所有程序P在所有的对象o1都替换成o2时,程序P的行为没有发生改变,那么类型T2是类型T1的子类型。换句话说,所有引用基类的地方必须能透明地使用其子类兑现
- 在使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类的方法
- 里氏替换原则告诉我们,继承实际上是让两个子类耦合性增强了,在适当的情况下,可以通过聚合、组合、依赖来解决问题。
package com.luguangyou.principle.livko;
//因为子类修改了父类中的方法,使得运算出现了错误,没有达到预期的效果
public class Livko1 {
public static void main(String[] args) {
Sum sum = new Sum();
System.out.println(sum.jianfa(5, 1));
System.out.println(sum.jianfa(6,12));
SubSum subSum = new SubSum();
System.out.println(subSum.jianfa(5, 1));
System.out.println(subSum.add(5,1));
}
}
class Sum{
public int jianfa(int num1,int num2){
return num1-num2;
}
}
class SubSum extends Sum{
public int jianfa(int a,int b){
return a+b;
}
public int add(int a,int b){
return 9+jianfa(a,b);
}
}
package com.luguangyou.principle.livko;
public class Livok2 {
public static void main(String[] args) {
Sum1 sum = new Sum1();
System.out.println(sum.jianfa(5, 1));
System.out.println(sum.jianfa(6,12));
SubSum1 subSum = new SubSum1();
System.out.println(subSum.jianfa(5, 1));
System.out.println(subSum.add(5,1));
System.out.println(subSum.func(5, 1));
}
}
class Base{
}
class Sum1 extends Base{
public int jianfa(int num1,int num2){
return num1-num2;
}
}
class SubSum1 extends Base{
//如果SubSum1需要使用Sum1的方法,使用组合关系
private Sum1 sum = new Sum1();
public int jianfa(int a,int b){
return a+b;
}
public int add(int a,int b){
return 9+jianfa(a,b);
}
//我们仍然想用Sum1的方法
public int func(int a,int b){
return this.sum.jianfa(a,b);
}
}
开闭原则
- 开闭原则是编程中最基础、最重要的设计原则
- 一个软件实体,如类、模块和函数应该对扩展开发(提供方)、对修改关闭(适用方)。用抽象构建框架,用实现展示细节
- 当软件要变化时,尽量通过扩展软件实体来实现变化,而不是通过修改代码来实现变化
- 编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则
package com.luguangyou.principle.ocp;
import java.awt.*;
public class ocp1 {
public static void main(String[] args) {
//实例圆形对象
Cricle cricle = new Cricle();
//实例化矩形对象
Rectangle rectangle = new Rectangle();
//实例化三角形对象
Triangle triangle = new Triangle();
//实例化使用者
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(cricle);
graphicEditor.drawShape(rectangle);
graphicEditor.drawShape(triangle);
}
}
//没有使用开闭原则时
class GraphicEditor{
//接收Shape对象,然后根据type的不同来绘制不同的图形
public void drawShape(Shape s){
if(s.type==1){
drawCircle(s);
}else if(s.type ==2){
drawRectangle(s);
}else if(s.type ==3){
drawTriangle(s);
}
}
//画圆形
public void drawCircle(Shape r){
System.out.println("绘制圆形");
}
//画矩形
public void drawRectangle(Shape r){
System.out.println("绘制矩形");
}
//画三角形
public void drawTriangle(Shape s){
System.out.println("绘制三角形");
}
}
class Shape{
int type;
}
class Cricle extends Shape{
public Cricle(){
super.type = 1;
}
}
class Rectangle extends Shape{
public Rectangle(){
super.type = 2;
}
}
class Triangle extends Shape{
public Triangle(){
super.type=3;
}
}
package com.luguangyou.principle.ocp;
public class ocp2 {
public static void main(String[] args) {
//实例圆形对象
Cricle1 cricle = new Cricle1();
//实例化矩形对象
Rectangle1 rectangle = new Rectangle1();
//实例化三角形对象
Triangle1 triangle = new Triangle1();
//实例化使用者
GraphicEditor1 graphicEditor = new GraphicEditor1();
graphicEditor.drawShape(cricle);
graphicEditor.drawShape(rectangle);
graphicEditor.drawShape(triangle);
}
}
//使用开闭原则
class GraphicEditor1{
public void drawShape(Shape1 s){
s.draw();
}
}
//定义一个接口Shape,Shape还是相当于一个基类
interface Shape1{
public void draw();
}
class Cricle1 implements Shape1{
@Override
public void draw() {
System.out.println("画一个圆形");
}
}
class Rectangle1 implements Shape1{
@Override
public void draw() {
System.out.println("画一个矩形");
}
}
class Triangle1 implements Shape1{
@Override
public void draw() {
System.out.println("画一个三角形");
}
}
迪米特法则(最少知道原则)
- 一个对象应该对其他对象保持最少的了解
- 类与类之间的关系越密切耦合度就越大
- 被依赖的类不管多么复杂,都应该讲逻辑封装在内部对外提供public方法,不对外泄漏任何信息
- 迪米特法则还有个更简单的定义:只于直接朋友通信
- 直接朋友的定义:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系我们就说这两个对象之间是朋友关系,耦合的方式很多,依赖、聚合、组合、关联等,其中我们称出现在成员变量、方法参数、方法返回值中的类称为直接的朋友,而出现在局部变量中的类不是直接朋友,也就是说,陌生的类最好不要以局部变量的形式出现在类的内部
注意事项和细节
- 迪米特法则的核心是降低类之间的耦合
- 但是注意:由于每个类都减少不必要的依赖,因此迪米特法则只要求降低类间耦合关系,并不是要求完全没有依赖关系
package com.luguangyou.principle.demeter;
import java.util.ArrayList;
import java.util.List;
public class Demeter1 {
public static void main(String[] args) {
//创建一个SchoolManager对象
SchoolManager schoolManager = new SchoolManager();
schoolManager.printAllEmployee(new CollegeManager());
}
}
//学校总部员工类
class Employee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//学院总部员工类
class CollegeEmployee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//管理学院员工的的管理类
class CollegeManager{
//返回学院的所有员工
public List<CollegeEmployee> getAllEmployee(){
List<CollegeEmployee> list = new ArrayList<>();
for(int i=0;i<10;i++){//这里我们增加十个员工到list
CollegeEmployee emp = new CollegeEmployee();
emp.setId("学院员工id"+i);
list.add(emp);
}
return list;
}
}
//学校管理类
/*
分析School类的直接朋友类有哪些Employee、CollegeManager
CollegeEmployee不是直接朋友而是一个陌生类,这样违背了迪米特法则
*/
class SchoolManager{
//返回学校总部的学员
public List<Employee> getAllEmployee(){
List<Employee> list = new ArrayList<>();
for(int i=0;i<5;i++){
Employee emp = new Employee();
emp.setId("学校总部员工id"+i);
list.add(emp);
}
return list;
}
//该方法完成输出学校总部和学院员工信息
void printAllEmployee(CollegeManager sub){
//分析问题
/*
1.这里的CollegeEmployee不是School的直接朋友
2.CollegeEmployee是以局部变量的方式出现在 SchoolManager中的
3.违反了迪米特法则
*/
//获取到学院员工
List<CollegeEmployee> list = sub.getAllEmployee();
System.out.println("-----学院员工------");
for(CollegeEmployee e:list){
System.out.println(e.getId());
}
//获取学校总部员工
List<Employee> list1 = this.getAllEmployee();
for(Employee employee:list1){
System.out.println(employee.getId());
}
}
}
package com.luguangyou.principle.demeter.improve;
import java.util.ArrayList;
import java.util.List;
public class improve {
public static void main(String[] args) {
System.out.println("使用迪米特法则");
SchoolManager schoolManager = new SchoolManager();
schoolManager.printAllEmployee(new CollegeManager());
}
}
//学校总部员工类
class Employee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//学院总部员工类
class CollegeEmployee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//管理学院员工的的管理类
class CollegeManager{
//返回学院的所有员工
public List<CollegeEmployee> getAllEmployee(){
List<CollegeEmployee> list = new ArrayList<>();
for(int i=0;i<10;i++){//这里我们增加十个员工到list
CollegeEmployee emp = new CollegeEmployee();
emp.setId("学院员工id"+i);
list.add(emp);
}
return list;
}
//打印学院员工信息
public void printAllCollegeManager(){
List<CollegeEmployee> list = this.getAllEmployee();
for (CollegeEmployee collegeEmployee : list) {
System.out.println(collegeEmployee.getId());
}
}
}
//学校管理类
/*
分析School类的直接朋友类有哪些Employee、CollegeManager
CollegeEmployee不是直接朋友而是一个陌生类,这样违背了迪米特法则
*/
class SchoolManager {
//返回学校总部的学员
public List<Employee> getAllEmployee() {
List<Employee> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Employee emp = new Employee();
emp.setId("学校总部员工id" + i);
list.add(emp);
}
return list;
}
//该方法完成输出学校总部和学院员工信息
void printAllEmployee(CollegeManager sub) {
//分析问题
/*
1.这里的CollegeEmployee不是School的直接朋友
2.CollegeEmployee是以局部变量的方式出现在 SchoolManager中的
3.违反了迪米特法则
*/
//获取到学院员工
sub.printAllCollegeManager();
//获取学校总部员工
List<Employee> list1 = this.getAllEmployee();
for (Employee employee : list1) {
System.out.println(employee.getId());
}
}
}
合成复用原则
合成复用原则是尽量使用合成/聚合方式而不是使用继承。