一、java设计模式经典面试题
1、原型设计模式问题
2、设计模式的七大原则
3、项目相关–金融借贷平台项目
4、解释器设计模式
5、单例设计模式
面试题:
单例设计模式一共有几种实现方式?请分别用代码实现,并说明各个实现方式的优缺点?
单例设计模式共有8种写法:
①饿汉式–两种
②懒汉式–三种
③双重检查
④静态内部类
⑤枚举
二、设计模式的重要性
①设计模式(design pattern)是对软件设计中普遍存在(反复出现)的各种问题,所提出的解决方案
②设计模式在软件哪里?—面向对象(oo)=>功能模块[设计模式 + 算法]=>框架[使用到多种设计模式]=>架构[服务器集群]
三、设计模式的七大原则
设计模式的目的:
编写软件过程中,程序员面临着来自耦合性、内聚性以及可维护性、可扩展性、重用性、灵活性等多方面挑战,设计模式是为了让程序(软件),具有更好的
- 代码重用性:相同功能的代码,不用多次编写
- 可读性:编程的规范性,便于其他程序员的阅读和理解
- 可扩展性(可维护性):当需要增加新的功能时,十分方便
- 可靠性:当增加新功能后,对原来功能没有影响
- 使程序呈现高内聚、低耦合的特性
设计模式原则:使程序员编程时,应当遵守的原则,也是各种设计模式的基础
设计模式常用的七大原则:
1、单一职责原则
①基本介绍
对类来说,是一个类应该只负责一项职责。如类A负责两个不同职责:职责1,职责2。当职责1需求变更而改变A时,可能造成职责2执行错误,所以需要将A的粒度分解为A1,A2
②应用实例
交通工具案例
方案一:
package single;
/**
* @ClassName SingleResponsibility1
* @Description TODO
**/
public class SingleResponsibility1 {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.run("摩托车");
vehicle.run("汽车");
vehicle.run("飞机");
}
}
//交通工具类
//方式1
//1.在方式1的run方法中,违反了单一职责原则
//2.解决方案:根据交通工具运行方法不同,分解成不同类
class Vehicle{
public void run(String vehicle){
System.out.println(vehicle + "在公路上运行");
}
}
方案2:
package single;
/**
* @ClassName SingleResponsibility2
* @Description TODO
**/
public class SingleResponsibility2 {
public static void main(String[] args) {
RoadVehicle roadVehicle = new RoadVehicle();
roadVehicle.run("摩托车");
roadVehicle.run("汽车");
AirVehicle airVehicle = new AirVehicle();
airVehicle.run("飞机");
}
}
//方案2
//1.遵守单一职责原则
//2.但是改动很大,将类分解,同时修改客户端
//3.改进:直接修改Vehicle类,改动的代码较少
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 + "在水中运行");
}
}
方案3:
package single;
/**
* @ClassName SingleResponsibility3
* @Description TODO
**/
public class SingleResponsibility3 {
public static void main(String[] args) {
Vehicle2 vehicle2 = new Vehicle2();
vehicle2.run("汽车");
vehicle2.runAir("飞机");
vehicle2.runWater("轮船");
}
}
//方式3
//1.这种修改方法没有对原来的类做大的修改,只是增加方法
//2.虽然没有在类这个级别上遵守单一职责原则,但在方法级别上,仍遵守单一职责原则
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 Segregation;
/**
* @ClassName Segregation1
* @Description TODO
**/
public class Segregation1 {
public static void main(String[] args) {
}
}
//接口
interface Interface1{
void operation1();
void operation2();
void operation3();
void operation4();
void operation5();
}
class B implements Interface1{
public void operation1(){
System.out.println("B 实现了 operation1");
}
public void operation2(){
System.out.println("B 实现了 operation2");
}
public void operation3(){
System.out.println("B 实现了 operation3");
}
public void operation4(){
System.out.println("B 实现了 operation4");
}
public void operation5(){
System.out.println("B 实现了 operation5");
}
}
class D implements Interface1{
public void operation1(){
System.out.println("D 实现了 operation1");
}
public void operation2(){
System.out.println("D 实现了 operation2");
}
public void operation3(){
System.out.println("D 实现了 operation3");
}
public void operation4(){
System.out.println("D 实现了 operation4");
}
public void operation5(){
System.out.println("D 实现了 operation5");
}
}
class A{//A类通过接口Interface1依赖(使用)B类,但只会用到123方法
public void depend1(Interface1 i){
i.operation1();
}
public void depend2(Interface1 i){
i.operation2();
}
public void depend3(Interface1 i){
i.operation3();
}
}
class C{//C类通过接口Interface1依赖(使用)D类,但只会用到145方法
public void depend1(Interface1 i){
i.operation1();
}
public void depend4(Interface1 i){
i.operation4();
}
public void depend5(Interface1 i){
i.operation5();
}
}
采用接口隔离原则后的类图
代码实现:
package Segregation;
/**
* @ClassName improve
* @Description TODO
**/
public class improve {
public static void main(String[] args) {
A a = new A();
a.depend1(new B());//A类通过接口依赖B
a.depend2(new B());
C c = new C();
c.depend1(new D());
c.depend4(new D());
}
}
//接口
interface Interface1{
void operation1();
}
interface Interface2{
void operation2();
void operation3();
}
interface Interface3{
void operation4();
void operation5();
}
class B implements Interface1,Interface2{
public void operation1(){
System.out.println("B 实现了 operation1");
}
public void operation2(){
System.out.println("B 实现了 operation2");
}
public void operation3(){
System.out.println("B 实现了 operation3");
}
}
class D implements Interface1,Interface3{
public void operation1(){
System.out.println("D 实现了 operation1");
}
public void operation4(){
System.out.println("D 实现了 operation4");
}
public void operation5(){
System.out.println("D 实现了 operation5");
}
}
class A{//A类通过接口Interface1,Interface2依赖(使用)B类,但只会用到123方法
public void depend1(Interface1 i){
i.operation1();
}
public void depend2(Interface2 i){
i.operation2();
}
public void depend3(Interface2 i){
i.operation3();
}
}
class C{//C类通过接口Interface1,Interface3依赖(使用)D类,但只会用到145方法
public void depend1(Interface1 i){
i.operation1();
}
public void depend4(Interface3 i){
i.operation4();
}
public void depend5(Interface3 i){
i.operation5();
}
}
3、依赖倒转(倒置)原则
①基本介绍
- 高层模块不应该依赖底层模块,二者都应依赖其抽象
- 抽象不应该依赖细节,细节应该依赖抽象
- 依赖倒转的中心思想是:面向接口编程
- 依赖倒转原则基于的设计理念:相对于细节的多变性,抽象的东西是要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在java中,抽象指:接口或抽象类,细节就是具体的实现类
- 使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成
②应用实例
编程完成Person接收消息的功能
package inversion;
/**
* @ClassName DependencyInversion
* @Description TODO
**/
public class DependencyInversion {
public static void main(String[] args) {
Person0 person = new Person0();
person.receive(new Email0());
}
}
class Email0{
public String getInfo(){
return "电子邮件信息: hello,world";
}
}
//完成Person接收消息的功能
//方式1
//1.简单,比较容易想到
//2.如果获取的对象是短信等,则新增类,同时Person也要增加相应的接收方法
//3.解决思路:引入一个抽象接口IReceiver,表示接受者,这样Person类与接口发生依赖
// 因为Email等属于接收的范围,各自实现TReceiver接口就可以
class Person0{
public void receive(Email0 email){
System.out.println(email.getInfo());
}
}
③依赖关系传递的三种方式和应用案例
接口传递
//方式1:通过接口传递实现依赖
//开关的接口
interface IOpenAndClose{
public void open(ITV tv);//抽象方法,接收接口
}
interface ITV{
public void play();
}
//实现接口
class OpenAndClose implements IOpenAndClose{
public void open(ITV tv){
tv.play();
}
}
实现代码:
ChangHong changHong = new ChangHong();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.open(changhong);
构造方法传递
//方式2:通过构造方法依赖传递
interface IOpenAndClose{
public void open(?);//抽象方法
}
interface ITV{
public void play();
}
class OpenAndClose implements IOpenAndClose{
public ITV tv;//成员
public OpenAndClose(ITV tv){//构造器
this.tv = tv;
}
public void open(){
this.tv.play();
}
}
实现代码:
OpenAndClose openAndClose = new OpenAndClose(changHong);
openAndClose.open();
setter方式传递
//方式3:通过setter方法传递
interface IOpenAndClose{
public void open();
public void setTv(ITV tv);
}
interface 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();
}
}
实现代码:
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.setTv(changHong);
openAndClose.open();
实例:
class ChangHong implements ITV{
@Override
public void play() {
System.out.println("长虹电视机打开");
}
}
④注意事项和细节
- 底层模块尽量有抽象类或接口,或者两者都有,程序稳定性更好
- 变量的生命类型尽量使抽象类或接口,这样变量引用和实际对象间就存在一个缓冲层,利于程序扩展和优化
- 继承时遵循里氏替换原则
4、里氏替换原则
①基本介绍
- 如果对每个类型T1的对象o1,都有类型为T2的对象o2,使得以T1定义的所有程序P在所有的对象o1都代换成o2时,程序P的行为没有发生变化,那么类型T2是类型T1的子类型。所有引用基类的地方必须能透明的使用其子类对象
- 使用继承时,遵循里氏替换原则,在子类张尽量不要重写父类的方法
- 继承实际上让两个类耦合性增强了,在适当的情况下,可以通过聚合、组合、依赖来解决问题
②实例
使用里氏替换原则后的关系图:
改进后代码:
//创建一个更基础的基类
class Base{
//把更基础的方法和成员写到Base类
}
//A类
class A extends Base{
//返回两个数的差
public int func1(int num1,int num2){
return num1 - num2;
}
}
//B类继承了A类
//增加了新功能:完成两个数相加,然后和9求和
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 func2(a,b) + 9;
}
//如果仍想用A的方法
public int func3(int a,int b){
return this.a.func1(a,b);
}
}
5、开闭原则
①基本介绍
- 开闭原则(OCP)是编程中最基础、最重要的设计原则
- 一个软件实体如类、模块和函数应该对扩展开放,对修改关闭,用抽象构建框架,用实现扩展细节
- 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化
- 编程中遵循其他原则,以及使用设计模式的目的是遵循开闭原则
②实例
package ocp;
/**
* @ClassName Ocp
* @Description TODO
**/
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){
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{
Rectangle(){
super.m_type = 1;
}
}
class Circle extends Shape{
Circle(){
super.m_type = 2;
}
}
方式1的优缺点:
优点:好理解,简单易操作
缺点:违反了设计模式的ocp原则,即对扩展开放,对修改关闭,即当我们给类增加新功能时,尽量不修改代码或尽可能少修改代码
改进后代码:
package ocp;
/**
* @ClassName Ocp
* @Description TODO
**/
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();
}
}
//基类
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("绘制圆形");
}
}
6、迪米特法则
①基本介绍
- 一个对象应该对其他对象保持最少的了解
- 类与类关系越密切,耦合度越大
- 迪米特法则又叫最少知道原则,即一个类对自己依赖的类知道的越少越好,也就是说,对于被依赖的类不管多复杂,都尽量将逻辑封装在类的内部,对外除了提供的public方法,不对外泄漏任何信息
- 此法则只与直接的朋友通信
②实例
有一个学校,下属有各个学院和总部,现要求打印出学校总部员工ID和学院员工的ID,编程实现以上功能
使用法则前代码:
package demeter;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName Demeter1
* @Description TODO
**/
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 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++){//增加10个员工到list
CollegeEmployee emp = new CollegeEmployee();
emp.setId("学院员工id=" + i);
list.add(emp);
}
return list;
}
}
//学校管理类
//CollegeEmployee 不是 直接朋友,而是一个陌生类,违背了迪米特法则
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,违反了迪米特法则
//获取到学院员工
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());
}
}
}
使用法则后的代码:
package demeter.improve;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName Demeter1
* @Description TODO
**/
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 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++){//增加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());
}
}
}
//学校管理类
//CollegeEmployee 不是 直接朋友,而是一个陌生类,违背了迪米特法则
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
sub.printEmployee();
//获取到学院总部员工
List<Employee> list2 = this.getAllEmployee();
System.out.println("-------------学校总部员工-------------");
for (Employee e : list2){
System.out.println(e.getId());
}
}
}
③注意事项和细节
迪米特法则的核心是降低类之间的耦合
注意:由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间(对象间)耦合关系,并不是要求完全没有依赖关系
7、合成复用原则
①基本介绍
原则是尽量使用合成/聚合的方式,而不是使用继承
8、总结–设计原则的核心思想
- 找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起
- 针对接口编程,而不是针对实现编程
- 为了交互对象之间的松耦合设计而努力
四、UML类图
1、基本介绍
- UML–统一建模语言,是一种用于软件系统分析和设计的语言工具,它用于帮助软件开发人员进行思考和记录思路的结果
- UML本身是一套符号的规定门用于描述软件模型中的各个元素和他们之间的关系,如:类、接口、实现、泛化、依赖、组合、聚合等
2、UML图
①用例图
②静态结构图:类图、对象图、包图、组件图、部署图
③动态行为图:交互图(时序图与协作图)、状态图、活动图
说明:类图是描述类与类之间的关系图,是UML图中最核心的
类之间的关系:依赖、泛化(继承)、实现、关联、聚合与组合
3、类图
①依赖关系
在类中用到了对方,就存在依赖关系
总结:
- 类中用到了对方
- 是类的成员属性
- 是方法的返回类型
- 是方法接收的参数类型
- 方法中使用到
②泛化关系
实际上是继承关系,是依赖关系的特例
总结:
泛化关系实际上是继承关系
如果A类继承了B类,就说A和B存在泛化关系
③实现关系
就是A类实现B类,是依赖关系的特例
④关联关系
是类与类之间的联系,是依赖关系的特例
具有导航型,分为单向关系或双向关系
⑤聚合关系
表示的是整体和部分的关系,整体和部分可以分开,聚合关系是关联关系的特例,具有关联的导航型和多重性,空心菱形的实线表示
如果不可分离,则升级为组合关系
⑥组合关系
也是整体与部分的关系,但整体与部分不可以分开