1.Java设计模式
一.内容介绍
设计模式是对软件设计中普遍存在的各种问题,所提出的解决方案。
二.七大原则
1.单一职责原则
对类来说,即一个类应该只负责一项职责。比如userDao只负责用户的职责。把一个类拆为多个类。
作用:1.降低类的复杂度,一个类只负责一项职责
2.提高类的可读性,可维护性
3.降低变更引起的风险、
4.在通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以违反;只有类中方法数量足够少,可以在方法级别保持单一原则。
案例:
package singleresponsibility;
public class Singleresponsibility {
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 + "在公路上跑");
}
}
单一职责优化案例:
package singleresponsibility;
public class Singleresponsibility2 {
public static void main(String[] args) {
RoadVehicle roadVehicle = new RoadVehicle();
roadVehicle.run("摩托");
AirVehicle airVehicle = new AirVehicle();
airVehicle.run("飞机");
WaterVehicle waterVehicle = new WaterVehicle();
waterVehicle.run("轮船");
}
}
//这种方案开销大
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+"在水里运行");
}
}
package singleresponsibility;
public class Singleresponsibility3 {
public static void main(String[] args) {
Vehicle2 vehicle2 = new Vehicle2();
vehicle2.run("汽车");
vehicle2.runAir("飞机");
vehicle2.runWater("船");
}
}
class Vehicle2 {
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 + "在水中运行");
}
}
2.接口隔离原则
客户端不应该依赖它不需要的接口,及一个类对另一个类的依赖应该建立在最小的接口上。
接口隔离原则:一个类对另一个类的依赖应该建立在最小的接口上
package segregation2;
import org.junit.Test;
public class Segregation1 {
public static void main(String[] args) {
A a = new A();
a.depend1(new B());//A类通过接口依赖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());
}
}
interface Interface1{
void opertion1();
}
interface Interface2{
void opertion2();
void opertion3();
}
interface Interface3{
void opertion4();
void opertion5();
}
class B implements Interface1,Interface2{
@Override
public void opertion1() {
// TODO Auto-generated method stub
System.out.println("B实现了opertion1");
}
@Override
public void opertion2() {
// TODO Auto-generated method stub
System.out.println("B实现了opertion2");
}
@Override
public void opertion3() {
// TODO Auto-generated method stub
System.out.println("B实现了opertion3");
}
}
class D implements Interface1,Interface3{
@Override
public void opertion1() {
// TODO Auto-generated method stub
System.out.println("D实现了opertion1");
}
@Override
public void opertion4() {
// TODO Auto-generated method stub
System.out.println("D实现了opertion4");
}
@Override
public void opertion5() {
// TODO Auto-generated method stub
System.out.println("D实现了opertion5");
}
}
class A{// A类通过接口Interface1依赖(使用)B类,但是只会用到1,2,3方法
public void depend1(Interface1 i) {
i.opertion1();
}
public void depend2(Interface2 i) {
i.opertion2();
}
public void depend3(Interface2 i) {
i.opertion3();
}
}
class C{// C类通过接口Interface1依赖(使用)B类,但是只会用到1,4,5方法
public void depend1(Interface1 i) {
i.opertion1();
}
public void depend4(Interface3 i) {
i.opertion4();
}
public void depend5(Interface3 i) {
i.opertion5();
}
}
3.依赖倒转原则
1.高层模块不要依赖底层模块,二者都应该依赖其抽象(接口或者抽象类)
2.抽象不应该依赖细节,细节应该依赖抽象
3.依赖倒转的中心思想是面向接口编程
4.抽象的东西要稳定
package inversion;
public class DependecyInversion {
public static void main(String[] args) {
Person person = new Person();
person.receive(new Email());
person.receive(new WeinXin());
}
}
//定义接口
interface IReceiver{
public String getInfo();
}
class Email implements IReceiver{
public String getInfo() {
return "电子邮件信息:helloworld";
}
}
class WeinXin implements IReceiver{
@Override
public String getInfo() {
// TODO Auto-generated method stub
return "微新信息:helloJava";
}
}
//完成person接受消息的功能
class Person{
public void receive(IReceiver receiver) {
System.out.println(receiver.getInfo());
}
}
补充:依赖关系传递的三种方式:
1.接口传递依赖
//方式1:通过接口传递实现依赖
//开关的接口
interface ITV{//ITV接口
public void play();
}
interface IOpenAndClose{//抽象方法接收接口
public void open(ITV tv);
}
//实现接口
class OpenAndClose implements IOpenAndClose{
public void open(ITV tv) {
tv.play();
}
}
接口传递依赖案例实现
public class DependencyTransmit {
public static void main(String[] args) {
ChangHong changHong = new ChangHong();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.open(changHong);//此处changHong实现了ITV接口所以能够被接收
}
}
interface ITV{//ITV接口
public void play();
}
interface IOpenAndClose{//抽象方法接收接口
public void open(ITV tv);
}
class ChangHong implements ITV{
public void play() {
System.out.println("长虹电视打开了...");
}
}
class OpenAndClose implements IOpenAndClose{
public void open(ITV tv) {
tv.play();
}
}
2.构造方法传递
//方式2:通过构造器口传递实现依赖
interface ITV{//ITV接口
public void play();
}
interface IOpenAndClose{//抽象方法接收接口
public void open();
}
//实现接口
class OpenAndClose implements IOpenAndClose{
private ITV tv;//成员
public OpenAndClose(ITV tv) {//通过构造器传递依赖
this.tv = tv;
}
public void open() {
this.tv.play();
}
}
构造方法传递依赖案例实现
public class DependencyTransmit {
public static void main(String[] args) {
ChangHong changHong = new ChangHong();
OpenAndClose openAndClose = new OpenAndClose(changHong);
openAndClose.open();
}
}
//方式2:通过构造器口传递实现依赖
interface ITV{//ITV接口
public void play();
}
interface IOpenAndClose{//抽象方法接收接口
public void open();
}
class ChangHong implements ITV{
public void play() {
System.out.println("长虹电视打开了...");
}
}
//实现接口
class OpenAndClose implements IOpenAndClose{
private ITV tv;//成员
public OpenAndClose(ITV tv) {//通过构造器传递依赖
this.tv = tv;
}
public void open() {
this.tv.play();
}
}
3.setter方式传递
interface ITV{//ITV接口
public void play();
}
interface IOpenAndClose{
public void open();
public void set(ITV tv);//set方法传递接口
}
//实现接口
class OpenAndClose implements IOpenAndClose {
private ITV tv;
public void set(ITV tv) {
this.tv = tv;
}
public void open() {
tv.play();
}
}
setter方式传递依赖实现
public class DependencyTransmit {
public static void main(String[] args) {
ChangHong changHong = new ChangHong();
//通过setter方法进行依赖传递
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.set(changHong);
openAndClose.open();
}
}
interface ITV{//ITV接口
public void play();
}
interface IOpenAndClose{//抽象方法接收接口
public void open();
public void set(ITV tv);
}
class ChangHong implements ITV{
public void play() {
System.out.println("长虹电视打开了...");
}
}
//实现接口
class OpenAndClose implements IOpenAndClose {
private ITV tv;
public void set(ITV tv) {
this.tv = tv;
}
public void open() {
tv.play();
}
}
4.里氏替换原则
1.引用基类的地方必须能够透明地使用其子类的对象。
2.在使用继承时,遵循里氏替换原则,在子类中尽量不要重新写父类的方法
3.里氏替换原则告诉我们,继承实际上让两个类耦合性增强类。在适当情况下,可以通过聚合,组合,依赖来解决问题。
问题展示:
public class Liskov {
public static void main(String[] args) {
A a = new A();
System.out.println("11-3="+a.func1(11,3));
System.out.println("------------------");
B b = new B();
System.out.println("11-3="+b.func1(11,3));//此处本意是输出11-3结果调用被重写的11+3
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{
@Override
public int func1(int a, int b) {
return a+b;
}
public int func2(int a, int b) {
return func1(a,b)+9;
}
}
使用里氏替换原则
public class Liskov {
public static void main(String[] args) {
A a = new A();
System.out.println("11-3="+a.func1(11,3));
System.out.println("------------------");
B b = new B();
//因为B类不再继承A类因此调用者不会再用func1是求减法
System.out.println("11-3="+b.func3(11,3));//这里本意是求出11-3
System.out.println("11+3+9="+b.func2(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;
}
public int func3(int a, int b) {
return this.a.func1(a,b);
}
}
5.开闭原则(核心)
1.模块和函数应该对扩展开放(对提供方),对修改关闭(对使用方);用抽象构建框架,用实现扩展细节。
2.当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
package ocp;
public class Ocp {
public static void main(String[] args) {
// TODO Auto-generated method stub
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
graphicEditor.drawShape(new Triangle());
}
}
//一个用于绘图的类
class GraphicEditor{
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("圆形");
}
//此处新增时,对使用方也进行了修改,违背了OCP原则
public void drawTriangle(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;
}
}
class Triangle extends Shape{
Triangle() {
super.m_type=3;
}
}
利用开闭原则后
package ocp.improve;
public class Ocp {
public static void main(String[] args) {
// TODO Auto-generated method stub
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
graphicEditor.drawShape(new Triangle());
graphicEditor.drawShape(new OtherGraphic());
}
}
//一个用于绘图的类
class GraphicEditor{
public void drawShape(Shape s) {
s.draw();
}
}
abstract class Shape{
int m_type;
public abstract void draw();//抽象方法
}
class Rectangle extends Shape{
Rectangle() {
super.m_type=1;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("绘制矩形");
}
}
class Circle extends Shape{
Circle() {
super.m_type=2;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("绘制圆形");
}
}
class Triangle extends Shape{
Triangle() {
super.m_type=3;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("绘制三角形");
}
}
//新增一个其它图形
class OtherGraphic extends Shape{
OtherGraphic(){
super.m_type=4;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("绘制其它图形");
}
}
6.迪米特原则
1.一个类应该对其它对象保持最少的了解
2.类与类关系越密切,耦合度越大
3.迪米特法则又称为最少知道原则,即一个类对自己依赖的类知道的越少越好,也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部,对外除了提供的public方法,不对外泄露任何信息。
4.只与直接的朋友通信(每个对象都会与其它对象有耦合关系,只有两个对象之间有耦合关系,那么这两个对象之间是朋友关系,耦合的方式有依赖,关联,组合,聚合等);成员变量,方法参数,方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接朋友,也就是说陌生的类最好不要以局部变量的形式出现在类的内部。
注意事项
1.迪米特法则的核心是降低类之间的耦合
2.每个类都减少了不必要的依赖,因此迪米特法则只是降低类之间(对象间)耦合关系,并不是完全没有依赖关系
未改进代码
public class Demeter1 {//客户端
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 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());
}
}
}
改进代码
public class Demeter1 {//客户端
public static void main(String[] args) {
System.out.println("~~~使用迪米特法则的改进~~~");
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 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 = 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++) { //这里我们增加了5个员工到 list
Employee emp = new Employee();
emp.setId("学校总部员工id= " + i);
list.add(emp);
}
return list;
}
//该方法完成输出学校总部和学院员工信息(id)
void printAllEmployee(CollegeManager sub) {
//分析问题
//1.这里的CollegeEmployee不是SchoolManager的直接朋友
//2.CollegeEmployee 是以局部变量方式出现再SchoolManager
//3.违反了迪米特原则
//将输出学院员工方法,封装到CollegeManager中
sub.printEmployee();
//获取到学校总部员工
List<Employee> list2 = this.getAllEmployee();
System.out.println("------------学校总部员工------------");
for (Employee e : list2) {
System.out.println(e.getId());
}
}
}
7.合成复用原则
原则是尽量使用合成/聚合(详细解释查看下一节UML类图讲解)的方式,而不是使用继承
中心思想
1.找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起
2.针对接口编程,而不是针对实现编程
3.为了交互对象之间的松耦合设计而努力
参考资料:B站up 尚硅谷