1、设计模式的目的:
- 编写软件的过程中,我们面临着来自耦合性,内聚性以及可维护性,可扩展性,重用性,灵活性等多方面的挑战,设计模式是为了让程序(软件)具有更好的代码重用性,可读性,可扩展性,可靠性(当我们增加新的功能时,对原来的功能没有影响
),使程序呈现高内聚,低耦合的特性。 - 设计模式包含了面向对象的精髓,“懂了设计模式,你就懂了面向对象分析和设计(OOA/D)的精要”
2、设计模式常用的七大原则:
设计模式的原则,其实就是我们在编程时,应当遵守的原则,也是各种设计模式的基础(即:设计模式为什么这样设计的依据)
2.1、 单一职责原则:
-
基本介绍:
对类来说的,即一个类应该只负责一项职责,如类A负责两个不同职责:职责1,职责2.当职责1需求变更而改变A时,可能造成职责2执行错误,所以需要将类A的粒度分解为A1,A2 -
示例:
public class Single {
public static void main(String[] args) {
Transportation transportation=new Transportation();
transportation.run("火车");
transportation.run("飞机");
}
public static class Transportation{
public void run(String way){
System.out.println(way+"在地上跑");
}
}
}
可以看到让一个类做两件事儿,上述写法就容易出错,不易维护,接着我们按照单一职责原则改进一下写法。
public class SingleOne {
public static void main(String[] args) {
TransportOne transportOne=new TransportOne();
transportOne.run("火车");
TransportTwo transportTwo=new TransportTwo();
transportTwo.run("飞机");
TransportThree transportThree=new TransportThree();
transportThree.run("潜艇");
}
public static class TransportOne{
public void run(String way){
System.out.println(way+"在地上跑");
}
}
public static class TransportTwo{
public void run(String way){
System.out.println(way+"在天上飞");
}
}
public static class TransportThree{
public void run(String way){
System.out.println(way+"在水里游");
}
}
}
上述写法虽然实现了单一职责原则但开销较大,我们还可以用另一种写法实现。
public class SingleTwo {
public static void main(String[] args) {
Transport transport=new Transport();
transport.runOne("火车");
transport.runTwo("飞机");
transport.runThree("潜艇");
}
public static class Transport{
public void runOne(String way){
System.out.println(way+"在地上跑");
}
public void runTwo(String way){
System.out.println(way+"在天上飞");
}
public void runThree(String way){
System.out.println(way+"在水里游");
}
}
}
可以看到,上述代码虽然实现了我们的目的,但并没有遵守单一职责原则,因为代码逻辑非常简单。
3. 单一职责原则注意事项和细节:
(1)降低类的复杂度,一个类只负责一项职责。
(2)提高类的可读性,可维护性。
(3)降低变更引起的风险。
(4)通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码级违反单一职责原则;只有类中方法数量足够少,可以在方法级别保持单一职责原则。
2.2、接口隔离原则(Interface Segregation Princple):
- 基本介绍:
客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上。
2.3、依赖倒转原则(Dependence Inversion Priniiple):
- 基本介绍:
(1)高层模块不应该依赖底层模块,二者都应该依赖其抽象
(2)抽象不应该依赖细节,细节应该依赖抽象
(3)依赖倒转(倒置)的中心思想是面向接口编程
(4)依赖倒转原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在java中,抽象指的是接口或抽象类,细节就是具体的实现类
(5)使用接口或抽象类的目的就是制定好规范,而不涉及具体的操作,把展现细节的任务交给他们的实现类去完成 - 应用实例:编程完成Person接收消息的功能
(1)传统方法:
public class TestOne {
public static void main(String[] args) {
Person person = new Person(new Email());
}
}
class Email{
public String getMessage(){
return "Email:Hello World";
}
}
class Person{
public Person(Email email){
System.out.println(email.getMessage());
}
}
看到结果,让我们一起想一下这个问题:如果我想换一种方式显示信息呢?比如:WeiXin:Hello World,等其它方式呢?所以让我们换另一种方式去实现
(2)用接口实现:
public class TestTwo {
public static void main(String[] args) {
Person person = new Person();
person.receive(new Email());
person.receive(new WeiXin());
}
}
//只需要增加一个接口即可
interface Receive{
public String getMessage();
}
class Email implements Receive{
public String getMessage(){
return "Email:Hello World";
}
}
class WeiXin implements Receive{
@Override
public String getMessage() {
return "WeiXin:Hello World";
}
}
class Person{
public void receive(Receive receive){
System.out.println(receive.getMessage());
}
}
- 依赖关系传递的三种方式和应用案例:
(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();
}
}
(2)构造方法传递:
interface IOpenAndClose{
public void open();//抽象方法
}
interface ITV{//ITV接口
public void play();
}
//实现接口
class OpenAndClose implements IOpenAndClose{
public ITV tv;//成员
public class OpenAndClose(ITV tv){//构造器
this.tv=tv;
}
public void open(ITv tv){
this.tv.play();
}
}
(3)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 class setTv(ITV tv){
this.tv=tv;
}
public void open(ITv tv){
this.tv.play();
}
}
- 依赖倒转原则的注意事项和细节
(1)底层模块尽量都要有抽象类或接口,或者两者都有,程序稳定性更好。
(2)变量的声明类型尽量是抽象类或接口,这样我们的变量引用和实际对象间就存在一个缓冲层,利于程序扩展和优化
(3)继承时遵循里氏替换原则
2.4、里氏替换原则:
1、OO中的继承性的思考和说明:
(1)继承包含这样一层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契约,虽然它不强制要求所有的子类必须遵循这些契约,但是如果子类对这些实现的方法任意修改,就会对整个继承体系造成破坏。
(2)继承在给程序设计带来便利的同时,也带来了弊端。比如使用继承会给程序带来侵入性,程序的可移植性降低,增加对象间的耦合性,如果一个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且父类修改后,所有涉及到子类的功能都有可能产生故障。
示例:
public class ReplaceTest {
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));//本意是求出11-3的结果
System.out.println("1-8="+b.func1(1,8));//本意是求出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{
//重写了父类的方法,这种重写可能是无意的
//增加了一个新功能,完成两个数相加,然后和9求和
public int func1(int a, int b) {
return a+b;
}
public int func2(int a,int b){
return func1(a,b)+9;
}
}
(3)问题提出:在编程中,如何正确的使用继承?=》里氏替换原则
2、基本介绍:
(1)里氏替换原则(Liskov Substitution Princple)在1988年,由麻省理工学院的一位姓里的女士提出来的。
(2)所有引用基类的地方必须能透明地使用其子类的对象。
(3)在使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类的方法。
(4)里氏替换原则告诉我们,继承实际上让两个类耦合性增强了,在适当的情况下,可以通过聚合,组合,依赖来解决问题。
(5)通用的做法是:原来的父类和子类都继承一个更通俗的基类,原有的继承关系去掉,采用依赖,聚合,组合等关系代替。
示例:
public class ReplaceTestTwo {
public static void main(String[] args) {
A1 a=new A1();
System.out.println("11-3="+a.func1(11,3));
System.out.println("1-8="+a.func1(1,8));
System.out.println("-------------------------");
B1 b=new B1();
//因为B类不在继承A类,因此调用者不会在想到fun1是求减法了
System.out.println("11+3="+b.func1(11,3));//本意是求出11-3的结果
System.out.println("1+8="+b.func1(1,8));//本意是求出1-8的结果
System.out.println("11+3+9="+b.func2(11,3));
//使用组合任然可以使用到A类相关方法,但A和B的耦合性大大降低了
System.out.println("11-3="+b.fun3(11,3));
}
}
//创建一个更加基础的类
class Base{
//把更加基础的写法和成员写到Base类
}
class A1 extends Base{
public int func1(int num1,int num2){
return num1-num2;
}
}
class B1 extends Base{
//如果B需要使用A类的方法,使用组合关系
private A1 a=new A1();
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 fun3(int a,int b){
return this.a.func1(a,b);
}
}
2.5、开闭原则:
基础版示例:
public class Ocp {
public static void main(String[] args) {
GraphicEditor graphicEditor=new GraphicEditor();
graphicEditor.drawRectangle(new Rectangle());
graphicEditor.drawCircle(new Circle());
}
}
//绘图类
class GraphicEditor{
//接收Shape对象,然后根据type,来绘制不同的图形
public void drawShape(Shape s){
if(s.m_type==1) drawRectangle(s);
if(s.m_type==2) drawCircle(s);
}
//绘制矩形
public void drawRectangle(Shape r){
System.out.println("绘制矩形!");
}
//绘制圆形
public void drawCircle(Shape r){
System.out.println("绘制圆形!");
}
}
//shape类,基类
class Shape{
int m_type;
}
//矩形
class Rectangle extends Shape{
Rectangle(){
super.m_type=1;
}
}
//圆形
class Circle extends Shape{
Circle(){
super.m_type=2;
}
}
分析:比较好理解,简单易操作,但违反了开闭原则(即对修改关闭(使用方),对扩展开发(提供方)),即当我们给类增加新功能的时候,尽量不修改代码或尽可能少修改代码。
基础版增加绘制三角形功能示例:
public class Ocp {
public static void main(String[] args) {
GraphicEditor graphicEditor=new GraphicEditor();
graphicEditor.drawRectangle(new Rectangle());
graphicEditor.drawCircle(new Circle());
graphicEditor.drawTriangle(new Triangle());
}
}
//绘图类
class GraphicEditor{
//接收Shape对象,然后根据type,来绘制不同的图形
public void drawShape(Shape s){
if(s.m_type==1) drawRectangle(s);
if(s.m_type==2) drawCircle(s);
//改动3
if(s.m_type==3)drawTriangle(s);
}
//绘制矩形
public void drawRectangle(Shape r){
System.out.println("绘制矩形!");
}
//绘制圆形
public void drawCircle(Shape r){
System.out.println("绘制圆形!");
}
//改动1:绘制三角形
public void drawTriangle(Shape r){
System.out.println("绘制三角形");
}
}
//shape类,基类
class Shape{
int m_type;
}
//矩形
class Rectangle extends Shape{
Rectangle(){
super.m_type=1;
}
}
//圆形
class Circle extends Shape{
Circle(){
super.m_type=2;
}
}
//改动2:新增三角形
class Triangle extends Shape{
Triangle(){
super.m_type=3;
}
}
可以看到至少改动了3处
基于OCP原则进行改进:
改进思路:将Shape类改进为抽象类,并提供一个抽象方法draw方法,让子类去实现即可,这样有新的图形种类时,只需要让新的图形类继承Shape,并实现draw方法即可,使用方的代码就不需要修改,满足开闭原则。
public class Ocp {
public static void main(String[] args) {
GraphicEditor graphicEditor=new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
}
}
//绘图类
class GraphicEditor{
//接收Shape对象,然后根据type,来绘制不同的图形
public void drawShape(Shape s){
s.draw();
}
}
//shape类,基类
abstract class Shape{
int m_type;
public abstract void draw();//抽象方法
}
//矩形
class Rectangle extends Shape{
Rectangle(){
super.m_type=1;
}
@Override
public void draw() {
System.out.println("绘制矩形");
}
}
//圆形
class Circle extends Shape{
Circle(){
super.m_type=2;
}
@Override
public void draw() {
System.out.println("绘制圆形");
}
}
新增绘制三角形功能:
分析:代码满足OCP原则,对修改关闭,对扩展开放
2.6迪米特法则
2.6.1基本介绍:
(1)一个对象应该对其他对象保持最少的了解
(2)类与类关系越密切,耦合度越大
(3)迪米特法则(Demeter Principle)又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部。对外除了提供的public方法,不对外泄露任何信息。
(4)迪米特法则还有个更简单的定义:只与直接的朋友通信
(5)直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。耦合的方式很多,依赖,关联,组合,耦合等。其中,我们称出现成员变量,方法参数,方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的内部。
2.6.2应用实例:
(1)有一个学校,下属有各个学院和总部,现要求打印出学校总部员工ID和学院员工的id
(2)编程实现上面的功能,看代码演示:
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<CollegeEmployee>();
for (int i=0;i<10;i++){
CollegeEmployee emp=new CollegeEmployee();
emp.setId("学院员工id= "+i);
list.add(emp);
}
return list;
}
}
//学校管理类
//分析SchoolManager类的直接朋友类有哪些Employee、CollegeManager
//CollegeEmployee不是直接朋友而是一个陌生类,这样违背了迪米特法则
class SchoolManager{
//返回学校总部的员工
public List<Employee> getAllEmployee(){
ArrayList<Employee> list= new ArrayList<>();
for (int i=0;i<5;i++){
Employee employee = new Employee();
employee.setId("学校总部员工id= "+i);
list.add(employee);
}
return list;
}
//输出学校总部和学院员工信息
void printAllEmployee(CollegeManager sub){
//分析问题
//这里的CollegeEmployee 不是SchoolManager的直接朋友
//CollegeEmployee是以局部变量方式出现在SchoolManager
//违反了迪米特法则
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());
}
}
}
改进:
import java.util.ArrayList;
import java.util.List;
public class Demeter1 {
public static void main(String[] args) {
System.out.println("---------使用迪米特法则进行改进----------");
//创建了一个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<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());
}
}
}
//学校管理类
//分析SchoolManager类的直接朋友类有哪些Employee、CollegeManager
//CollegeEmployee不是直接朋友而是一个陌生类,这样违背了迪米特法则
class SchoolManager{
//返回学校总部的员工
public List<Employee> getAllEmployee(){
ArrayList<Employee> list= new ArrayList<>();
for (int i=0;i<5;i++){
Employee employee = new Employee();
employee.setId("学校总部员工id= "+i);
list.add(employee);
}
return list;
}
//输出学校总部和学院员工信息
void printAllEmployee(CollegeManager sub){
//分析问题
//这里的CollegeEmployee 不是SchoolManager的直接朋友
//CollegeEmployee是以局部变量方式出现在SchoolManager
//违反了迪米特法则
//所以将输出学院员工的方法,封装到CollegeManager
/*List<CollegeEmployee>list1=sub.getAllEmployee();
System.out.println("---------学院员工-------------");
for (CollegeEmployee e:list1){
System.out.println(e.getId());
}*/
sub.printEmployee();
List<Employee>list2=this.getAllEmployee();
System.out.println("---------学校总部员工-------------");
for (Employee e:list2){
System.out.println(e.getId());
}
}
}
2.6.3总结:
1、迪米特法则注意事项和细节:
(1)迪米特法则的核心是降低类之间的耦合
(2)但是注意:由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间(对象间)耦合关系,并不是要求完全没有依赖关系
2.7合成复用原则
2.7.1基本介绍:
原则是尽量使用合成或聚合的方式,而不是使用继承。
3设计原则核心思想
(1)找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起。
(2)针对接口编程,而不是针对实现编程。
(3)为了交互对象之间的松耦合设计而努力。