学习

什么是设计模式

设计模式是在软件设计中反复出现的问题的通用解决方案。它们是经验丰富的软件开发人员总结出的最佳实践,可以帮助开发人员编写可重用、可维护和可扩展的代码

设计模式主要分为三大类:创建型模式、结构型模式和行为型模式

设计原则

  1. 开闭原则:对扩展开放,对修改关闭。去扩展而不是修改

  2. 单一职责原则:控制类的粒度大小、将对象解耦、提高其内聚性。低耦合高内聚

  3. 里氏替换原则:使用基类或父类对象去指向子类对象

  4. 依赖倒置原则:要面向接口编程,不要面向实现编程。具体实现应该依赖于抽象

  5. 接口隔离原则:要为各个类建立它们需要的专用接口。【接口尽量专用、单一】

    用多个专门的接口,而不使用单一的总接口,客户端不应该依赖它不需要的接口。一个类对一个类的依赖应该建立在最小的接口上。

    建立单一接口,不要建立庞大臃肿的接口尽量细化接口,接口中的方法尽量少,尽量细化接口。注意适度原则,一定要适度。不能滥用

  6. 迪米特法则:只与你的直接朋友交谈,不跟“陌生人”说话。最少知道原则

  7. 组合复用原则:尽量先使用组合或者聚合等关联关系来实现,其次才考虑使用继承关系来实现

    ​ 先组合,后继承。「包含」关系使用组合,「是」使用继承

设计模式示例

创建型模式

工厂方法模式、抽象工厂模式、单例模式、建造者模式和原型模式

单例模式

单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供一个全局访问点

在这个例子中,我们使用了一个私有的静态变量instance来存储唯一的实例,并通过构造函数私有化来实现懒加载。getInstance()方法用于获取唯一的实例,通过同步关键字synchronized确保线程安全。

1
2
3
4
5
6
7
8
9
10
11
12
public class Singleton {
private static Singleton instance;

private Singleton() {}

public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

工厂方法模式

工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式

在工厂模式中,创建对象的工作由一个工厂类完成,而不是直接通过调用构造函数来创建。在这个例子中,我们定义了一个接口Animal和两个实现类DogCatAnimalFactory类负责根据传入的类型参数创建相应的对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
interface Animal {
void speak();
}

class Dog implements Animal {
@Override
public void speak() {
System.out.println("汪汪");
}
}

class Cat implements Animal {
@Override
public void speak() {
System.out.println("喵喵");
}
}

class AnimalFactory {
public static Animal createAnimal(String type) {
if ("Dog".equalsIgnoreCase(type)) {
return new Dog();
} else if ("Cat".equalsIgnoreCase(type)) {
return new Cat();
}
return null;
}
}

抽象工厂模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 抽象产品接口
interface Animal {
void speak(); // 让动物发出声音的方法
}

// 具体产品接口
interface Cat implements Animal {
@Override
void speak(); // 实现猫类的具体行为
}

interface Dog implements Animal {
@Override
void speak(); // 实现狗类的具体行为
}

// 抽象工厂接口
interface AnimalFactory {
Animal createAnimal(); // 创建动物对象的方法
}

// 具体工厂1:创建猫对象
class CatFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Cat(); // 返回一个新的Cat对象
}
}

// 具体工厂2:创建狗对象
class DogFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Dog(); // 返回一个新的Dog对象
}
}

建造者模式

使用建造者模式,我们可以将产品的构建过程分解为多个部分,并且可以将每个部分的实现细节封装在不同的具体建造者类中。这样可以降低客户端和具体建造者之间的耦合度,提高代码的可维护性和扩展性。同时,如果需要添加新的构建部分,只需要创建一个新的具体建造者类即可,而不需要修改客户端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 产品类
public class Product {
private String partA;
private String partB;
private String partC;

public void setPartA(String partA) {
this.partA = partA;
}

public void setPartB(String partB) {
this.partB = partB;
}

public void setPartC(String partC) {
this.partC = partC;
}

public void show() {
System.out.println("Product: " + partA + ", " + partB + ", " + partC);
}
}

// 抽象建造者类
public abstract class Builder {
protected Product product = new Product();

public abstract void buildPartA();
public abstract void buildPartB();
public abstract void buildPartC();

public Product getResult() {
return product;
}
}

// 具体建造者类A
public class ConcreteBuilderA extends Builder {
@Override
public void buildPartA() {
product.setPartA("Part A");
}

@Override
public void buildPartB() {
product.setPartB("Part B");
}

@Override
public void buildPartC() {
product.setPartC("Part C");
}
}

// 客户端代码
public class Client {
public static void main(String[] args) {
Builder builder = new ConcreteBuilderA();
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();
Product product = builder.getResult();
product.show();
}
}

原型模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 抽象原型类
public abstract class Prototype {
public abstract void operation();
}

// 具体原型类A
public class ConcretePrototypeA extends Prototype {
@Override
public void operation() {
System.out.println("ConcretePrototypeA: Operation A");
}
}

// 具体原型类B
public class ConcretePrototypeB extends Prototype {
@Override
public void operation() {
System.out.println("ConcretePrototypeB: Operation B");
}
}

// 客户端代码
public class Client {
public static void main(String[] args) {
Prototype prototypeA = new ConcretePrototypeA();
prototypeA.operation();

Prototype prototypeB = new ConcretePrototypeB();
prototypeB.operation();
}
}

行为型模式

责任链模式、命令模式、解释器模式、迭代器模式、中介者模式【类似代理模式、适配器模式】、备忘录模式、观察者模式、状态模式、策略模式、模板方法模式和访问者模式

观察者模式

观察者模式通常包括以下几个角色:

  1. Subject(主题):维护观察者列表,并在状态改变时通知所有观察者。
  2. Observer(观察者):定义一个更新方法,当主题状态改变时会被调用。
  3. 具体观察者类:实现Observer接口,重写update方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// 观察者接口
interface Observer {
void update(String message);
}

// 具体观察者类
class ConcreteObserver implements Observer {
private String name;

public ConcreteObserver(String name) {
this.name = name;
}

@Override
public void update(String message) {
System.out.println(name + " received message: " + message);
}
}

// 主题接口
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}

// 具体主题类
class ConcreteSubject implements Subject {
private List<Observer> observers;
private String message;

public ConcreteSubject() {
observers = new ArrayList<>();
}

@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}

@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}

@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(message);
}
}

public void setMessage(String message) {
this.message = message;
notifyObservers();
}
}

public class ObserverPatternDemo {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();

Observer observer1 = new ConcreteObserver("Observer 1");
Observer observer2 = new ConcreteOserver("Observer 2");
Observer observer3 = new ConcreteObserver("Observer 3");

subject.registerObserver(observer1);
subject.registerObserver(observer2);
subject.registerObserver(observer3);

subject.setMessage("Hello, observers!");
subject.removeObserver(observer2);
subject.setMessage("Another message for remaining observers.");
}
}

策略模式

策略模式是一种行为设计模式,它定义了一系列算法,并将每个算法封装在一个具有共同接口的独立类中,使得它们可以相互替换。策略模式让算法的变化独立于使用它们的客户端

示例一

我们定义了一个策略接口Strategy,以及三个具体的策略实现类ConcreteStrategyAConcreteStrategyBConcreteStrategyC。我们还创建了一个上下文类Context,用于维护一个策略对象的引用。在客户端代码中,我们可以根据需要切换不同的策略,而不需要修改客户端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public interface Strategy {
void execute();
}

public class ConcreteStrategyA implements Strategy {
@Override
public void execute() {
System.out.println("执行策略A");
}
}

public class ConcreteStrategyB implements Strategy {
@Override
public void execute() {
System.out.println("执行策略B");
}
}

public class ConcreteStrategyC implements Strategy {
@Override
public void execute() {
System.out.println("执行策略C");
}
}

public class Context {
private Strategy strategy;

public Context(Strategy strategy) {
this.strategy = strategy;
}

public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}

public void executeStrategy() {
strategy.execute();
}
}


public class Client {
public static void main(String[] args) {
// 创建具体策略对象
Strategy strategyA = new ConcreteStrategyA();
Strategy strategyB = new ConcreteStrategyB();
Strategy strategyC = new ConcreteStrategyC();

// 创建上下文对象,并设置策略
Context context = new Context(strategyA);
context.executeStrategy(); // 输出:执行策略A

// 更改策略
context.setStrategy(strategyB);
context.executeStrategy(); // 输出:执行策略B

context.setStrategy(strategyC);
context.executeStrategy(); // 输出:执行策略C
}
}
示例二
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public interface Strategy {
void execute();
}

// bean 名称同时代表策略名称
@Component("strategyA")
public class ConcreteStrategyA implements Strategy {
@Override
public void execute() {
System.out.println("执行策略A");
}
}

// bean 名称同时代表策略名称
@Component("strategyB")
public class ConcreteStrategyB implements Strategy {
@Override
public void execute() {
System.out.println("执行策略B");
}
}

// bean 名称同时代表策略名称
@Component("strategyC")
public class ConcreteStrategyC implements Strategy {
@Override
public void execute() {
System.out.println("执行策略C");
}
}

@Service
public class StrategyService {
@Autowired
private ApplicationContext applicationContext;

// 根据策略名称找到策略 bean 对象,执行策略方法
public void executeStrategyByName(String name) {
Strategy strategy = (Strategy) applicationContext.getBean(name, Strategy.class);
if(strategy != null) {
strategy.execute();
} else {
throw new RuntimeException("策略不存在");
}
}
}

模板方法模式

模板方法模式是一种行为型设计模式,它在一个抽象类中定义了一个算法的骨架,将一些步骤的具体实现延迟到子类中。这样,子类可以在不改变该算法结构的情况下,重新定义算法中的某些特定步骤。

模板方法模式的主要角色有:

  1. 抽象类(Template):定义一个算法的骨架,包含一些抽象方法,用于定义算法中的步骤。
  2. 具体类(ConcreteClass):实现抽象类中的抽象方法,完成算法中的具体步骤。
  3. 客户端(Client):使用具体类的对象,调用抽象类中的方法,实现算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public abstract class AbstractClass {
// 定义一个模板方法,final 修饰,子类不能重写该方法
public final void templateMethod() {
try {
// 基类执行一些操作
doSomethingAbstractClass();

// 子类执行一些操作
doSomething();
} finally {
// 清理资源
cleanup();
}
}

// 具体方法,不支持子类重写
private void doSomethingAbstractClass() {
System.out.println("AbstractClass: Doing something...");
}

// 抽象方法,由子类实现
protected abstract void doSomething();

// 具体方法,支持子类重写
protected void cleanup() {
// 清理资源的代码
System.out.println("AbstractClass: cleanup");
}
}

public class ConcreteClassA extends AbstractClass {
@Override
protected void doSomething() {
// 具体的业务逻辑处理A
System.out.println("ConcreteClassA: Doing something...");
}

// 重写 clean
@Override
protected void cleanup() {
super.cleanup();
System.out.println("ConcreteClassA: cleanup");
}
}

public class ConcreteClassB extends AbstractClass {
@Override
protected void doSomething() {
// 具体的业务逻辑处理B
System.out.println("ConcreteClassB: Doing something else...");
}
}

public class Main {
public static void main(String[] args) {
AbstractClass concreteA = new ConcreteClassA();
concreteA.templateMethod();

System.out.println();

AbstractClass concreteB = new ConcreteClassB();
concreteB.templateMethod();
}
}

责任链模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public interface Handler {
void setNext(Handler handler);
void handleRequest(String request);
}

public class ConcreteHandler1 implements Handler {
private Handler next;

@Override
public void setNext(Handler handler) {
this.next = handler;
}

@Override
public void handleRequest(String request) {
System.out.println("ConcreteHandler1 handled " + request);

if (next != null) {
next.handleRequest(request);
} else {
System.out.println("No next handler found for " + request);
}
}
}

public class ConcreteHandler2 implements Handler {
private Handler next;

@Override
public void setNext(Handler handler) {
this.next = handler;
}

@Override
public void handleRequest(String request) {
System.out.println("ConcreteHandler2 handled " + request);

if (next != null) {
next.handleRequest(request);
} else {
System.out.println("No next handler found for " + request);
}
}
}

public class Client {
public static void main(String[] args) {
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();

handler1.setNext(handler2);

handler1.handleRequest("request");
}
}

命令模式

与适配器模式类似

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public interface Command {
void execute(String msg);
}

public class ConcreteCommand implements Command {
private Receiver receiver;

public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}

@Override
public void execute(String msg) {
receiver.action(msg);
}
}

public class Receiver {
public void action(String msg) {
System.out.println("执行命令:" + msg);
}
}

public class Client {
public static void main(String[] args) {
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
command.execute("hello,world");
}
}

访问者模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public interface Element {
void accept(Visitor visitor);
}

public class ConcreteElement implements Element {
private String name;

public ConcreteElement(String name) {
this.name = name;
}

@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}

public String getName() {
return name;
}
}

public interface Visitor {
void visit(ConcreteElement element);
}

public class ConcreteVisitor implements Visitor {
@Override
public void visit(ConcreteElement element) {
System.out.println("访问元素:" + element.getName());
}
}

public class Client {
public static void main(String[] args) {
Element element1 = new ConcreteElement("元素1");
Visitor visitor = new ConcreteVisitor();
element1.accept(visitor);
}
}

状态模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public interface State {
void handle(Context context);
}

public class ConcreteStateA implements State {
@Override
public void handle(Context context) {
System.out.println("当前状态为A");
context.setState(new ConcreteStateB());
}
}

public class ConcreteStateB implements State {
@Override
public void handle(Context context) {
System.out.println("当前状态为B");
context.setState(new ConcreteStateA());
}
}

public class Context {
private State state;

public Context(State state) {
this.state = state;
}

public void setState(State state) {
this.state = state;
}

public void request() {
state.handle(this);
}
}

public class Client {
public static void main(String[] args) {
Context context = new Context(new ConcreteStateA());
context.request(); // 输出:当前状态为A
context.request(); // 输出:当前状态为B
context.request(); // 输出:当前状态为A
}
}

结构型模式

适配器模式、桥接模式、装饰器模式、组合模式、外观模式、享元模式和代理模式

适配器模式

适配器模式是一种结构型设计模式,它允许将不兼容的接口转换为兼容的接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public interface Target {
void request();
}

public class Adaptee {
public void specificRequest() {
System.out.println("Adaptee 的 specificRequest 方法被调用");
}
}

public class Adapter implements Target {
private Adaptee adaptee;

public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}

@Override
public void request() {
adaptee.specificRequest();
}
}

public class Client {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.request();
}
}

桥接模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// 抽象类1
public abstract class Shape {
protected DrawAPI drawAPI;

public void setDrawAPI(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}

public abstract void draw();
}

// 具体类1
public class Circle extends Shape {
@Override
public void draw() {
drawAPI.drawCircle();
}
}

// 具体类2
public class Rectangle extends Shape {
@Override
public void draw() {
drawAPI.drawRectangle();
}
}

// 接口
public interface DrawAPI {
void drawCircle();
void drawRectangle();
}

// 实现类1
public class RedPenAPI implements DrawAPI {
@Override
public void drawCircle() {
System.out.println("Drawing a red circle with pen");
}

@Override
public void drawRectangle() {
System.out.println("Drawing a red rectangle with pen");
}
}

// 实现类2
public class BluePenAPI implements DrawAPI {
@Override
public void drawCircle() {
System.out.println("Drawing a blue circle with pen");
}

@Override
public void drawRectangle() {
System.out.println("Drawing a blue rectangle with pen");
}
}

// 客户端代码
public class Client {
public static void main(String[] args) {
Shape shape1 = new Circle();
shape1.setDrawAPI(new RedPenAPI());
shape1.draw();

Shape shape2 = new Rectangle();
shape2.setDrawAPI(new BluePenAPI());
shape2.draw();
}
}

装饰器模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 抽象组件
public interface Component {
void operation();
}

// 具体组件
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("ConcreteComponent: Doing operation");
}
}

// 抽象装饰类
public abstract class Decorator implements Component {
protected Component component;

public Decorator(Component component) {
this.component = component;
}

@Override
public void operation() {
component.operation();
}
}

// 具体装饰类A
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}

@Override
public void operation() {
System.out.println("ConcreteDecoratorA: Adding behavior A");
super.operation();
}
}

// 具体装饰类B
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}

@Override
public void operation() {
System.out.println("ConcreteDecoratorB: Adding behavior B");
super.operation();
}
}

// 客户端代码
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Component decoratorA = new ConcreteDecoratorA(component);
Component decoratorB = new ConcreteDecoratorB(decoratorA);

decoratorB.operation();
}
}

组合模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.ArrayList;
import java.util.List;

// 抽象组件
interface Component {
void operation();
}

// 叶子节点
class Leaf implements Component {
private String name;

public Leaf(String name) {
this.name = name;
}

@Override
public void operation() {
System.out.println("Leaf " + name + " operation.");
}
}

// 容器组件
class Composite implements Component {
private String name;
private List<Component> children = new ArrayList<>();

public Composite(String name) {
this.name = name;
}

public void add(Component child) {
children.add(child);
}

public void remove(Component child) {
children.remove(child);
}

@Override
public void operation() {
System.out.println("Composite " + name + " operation.");
for (Component child : children) {
child.operation();
}
}
}

// 客户端代码
public class Client {
public static void main(String[] args) {
// 创建树叶节点
Leaf leaf1 = new Leaf("Leaf1");
Leaf leaf2 = new Leaf("Leaf2");
Leaf leaf3 = new Leaf("Leaf3");

// 创建容器组件
Composite composite1 = new Composite("Composite1");
Composite composite2 = new Composite("Composite2");
Composite composite3 = new Composite("Composite3");

// 组装对象树
composite1.add(leaf1);
composite2.add(composite1);
composite3.add(composite2);

// 执行操作
composite3.operation();
}
}

外观模式

它允许用户将与接口交互的复杂性隐藏起来,而只需要与外观类交互

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// 外观接口
interface Facade {
void operation();
}

// 具体外观类A
class ConcreteFacadeA implements Facade {
private SubSystemB subSystemB;
private SubSystemC subSystemC;

public ConcreteFacadeA(SubSystemB subSystemB, SubSystemC subSystemC) {
this.subSystemB = subSystemB;
this.subSystemC = subSystemC;
}

@Override
public void operation() {
subSystemB.operation();
subSystemC.operation();
}
}

// 具体外观类B
class ConcreteFacadeB implements Facade {
private SubSystemA subSystemA;
private SubSystemD subSystemD;

public ConcreteFacadeB(SubSystemA subSystemA, SubSystemD subSystemD) {
this.subSystemA = subSystemA;
this.subSystemD = subSystemD;
}

@Override
public void operation() {
subSystemA.operation();
subSystemD.operation();
}
}

// 子系统A
class SubSystemA {
public void operation() {
System.out.println("Operation A");
}
}

// 子系统B
class SubSystemB {
public void operation() {
System.out.println("Operation B");
}
}

// 子系统C
class SubSystemC {
public void operation() {
System.out.println("Operation C");
}
}

// 子系统D
class SubSystemD {
public void operation() {
System.out.println("Operation D");
}
}

// 客户端代码
public class Client {
public static void main(String[] args) {
// 创建具体外观类对象
Facade facadeA = new ConcreteFacadeA(new SubSystemB(), new SubSystemC());
Facade facadeB = new ConcreteFacadeB(new SubSystemA(), new SubSystemD());

// 执行操作
facadeA.operation();
facadeB.operation();
}
}

享元模式

它通过共享技术有效地支持大量细粒度的对象。在享元模式中,对象被共享而不是复制,从而提高了系统的性能和效率。类似于工厂方法模式,但不复制对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// 抽象享元接口
interface Flyweight {
void operation(String externalState);
}

// 具体享元类A
class ConcreteFlyweightA implements Flyweight {
private String intrinsicState;

public ConcreteFlyweightA(String intrinsicState) {
this.intrinsicState = intrinsicState;
}

@Override
public void operation(String externalState) {
// 执行操作
System.out.println("ConcreteFlyweightA: " + intrinsicState + ", " + externalState);
}
}

// 具体享元类B
class ConcreteFlyweightB implements Flyweight {
private String intrinsicState;

public ConcreteFlyweightB(String intrinsicState) {
this.intrinsicState = intrinsicState;
}

@Override
public void operation(String externalState) {
// 执行操作
System.out.println("ConcreteFlyweightB: " + intrinsicState + ", " + externalState);
}
}

// 享元工厂类
class FlyweightFactory {
private Map<String, Flyweight> flyweights = new HashMap<>();

public Flyweight getFlyweight(String key) {
Flyweight flyweight = flyweights.get(key);
if (flyweight == null) {
switch (key) {
case "A":
flyweight = new ConcreteFlyweightA("Intrinsic State A");
break;
case "B":
flyweight = new ConcreteFlyweightB("Intrinsic State B");
break;
default:
throw new IllegalArgumentException("Invalid key: " + key);
}
flyweights.put(key, flyweight);
}
return flyweight;
}
}

// 客户端代码
public class Client {
public static void main(String[] args) {
// 创建享元工厂对象
FlyweightFactory factory = new FlyweightFactory();

// 获取享元对象并执行操作
Flyweight flyweightA = factory.getFlyweight("A");
flyweightA.operation("External State A");

Flyweight flyweightB = factory.getFlyweight("B");
flyweightB.operation("External State B");
}
}

代理模式

它通过为一个对象提供一个代理对象来控制对该对象的访问。代理模式可以分为静态代理和动态代理两种类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 抽象主题接口
interface Subject {
void request();
}

// 真实主题类
class RealSubject implements Subject {
@Override
public void request() {
System.out.println("RealSubject: Handling request.");
}
}

// 代理接口
interface Proxy {
void processRequest();
}

// 静态代理类
class StaticProxy implements Proxy {
private RealSubject realSubject;

public StaticProxy(RealSubject realSubject) {
this.realSubject = realSubject;
}

@Override
public void processRequest() {
System.out.println("StaticProxy: Pre-processing before RealSubject's request.");
realSubject.request();
System.out.println("StaticProxy: Post-processing after RealSubject's request.");
}
}

// 动态代理类
class DynamicProxy implements InvocationHandler {
private Object target;

public DynamicProxy(Object target) {
this.target = target;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("DynamicProxy: Before processing request.");
Object result = method.invoke(target, args);
System.out.println("DynamicProxy: After processing request.");
return result;
}
}

// 客户端代码
public class Client {
public static void main(String[] args) {
// 创建真实主题对象
RealSubject realSubject = new RealSubject();

// 创建静态代理对象
StaticProxy staticProxy = new StaticProxy(realSubject);
staticProxy.processRequest();

// 创建动态代理对象
DynamicProxy dynamicProxy = new DynamicProxy(realSubject);
Subject proxySubject = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(),
realSubject.getClass().getInterfaces(), dynamicProxy);
proxySubject.request();
}
}