目录
1.责任链模式(Chain of Responsibility)
设计模式的目的
- 代码重用性
- 可读性
- 可扩展性
- 可靠性
- 高内聚低耦合
- 设计模式包含了面向对象的精髓,“懂得了设计模式,你就懂得了面向对象分析和设计的精要”
七大原则
- 单一职责:一个类只负责一项职责。
单一职责要注意的事项和细节:
降低类的复杂度,一个类只负责一项职责;
提高类的可读性,可维护性;
降低变更引起的风险;
通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码级违反单一职责原则;只有类中方法数量足够少,可以在方法级别保持单一职责原则。
- 接口分离原则:客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上。
- 依赖倒置原则:高层模块不应该依赖底层模块,两者都应该依赖于抽象;抽象不应该依赖细节,细节应该依赖抽象。简单说就是要求对抽象进行编程,不要对实现编程,这样就降低了客户与实现模块间的耦合。
- 里氏替换原则:任何基类可以出现的地方,子类一定可以出现.(子类可以扩展父类的功能,但不能改变父类原有的功能,即子类继承父类时,除添加新的方法完成增加新增功能外,尽量不要重写父类的方法)
- 开放封闭原则:对扩展开放,对修改关闭
- 迪米特法则:最少知识原则。只和你的直接朋友交谈,不和陌生人说话,即如果两个软件实体无须直接通信,那么不应该发生直接的相互调用,可以通过第三方转发该调用/其目的是降低类之间的耦合度,提高模块的相对独立性。
- 合成复用原则:尽量先使用组合或者聚合等关联关系来实现,其次是考虑使用继承关系来实现。通常类的复用分为继承复用和合成复用两种。(继承复用的缺点:破环了类的封装性;子类与父类的耦合都高;限制了复用的灵活性;采用组合或聚合复用优点:维持了类的封装性;对象间的耦合性低;复用的灵活性高)
设计模式总和(23种)
设计模式助记
创建型模式
1.抽象工厂模式(AbstractFactory)
public class AbstractFactory {
public static void main(String[] args) {
Factory factory1 = new Factory1();
ProductA productA = factory1.createProductA();
productA.info();
Factory factory2 = new Factory2();
ProductB productB = factory2.createProductB();
productB.info();
}
}
interface Factory {
public ProductA createProductA();
public ProductB createProductB();
}
class Factory1 implements Factory {
@Override
public ProductA createProductA() {
return new ProductA1();
}
@Override
public ProductB createProductB() {
return new ProductB1();
}
}
class Factory2 implements Factory {
@Override
public ProductA createProductA() {
return new ProductA2();
}
@Override
public ProductB createProductB() {
return new ProductB2();
}
}
interface ProductA {
public void info();
}
class ProductA1 implements ProductA {
@Override
public void info() {
System.out.println("产品的信息:A1");
}
}
class ProductA2 implements ProductA {
@Override
public void info() {
System.out.println("产品的信息:A2");
}
}
interface ProductB {
public void info();
}
class ProductB1 implements ProductB {
@Override
public void info() {
System.out.println("产品的信息:B1");
}
}
class ProductB2 implements ProductB {
@Override
public void info() {
System.out.println("产品的信息:B2");
}
}
2.生成器模式(Builder)
import java.util.*;
public class Main {
public static void main(String[] args) {
Director director = new Director();
Builder builder1 = new Builder1();
director.Construct(builder1);
Product product1 = builder1.getResult();
product1.show();
Builder builder2 = new Builder2();
director.Construct(builder2);
Product product2 = builder2.getResult();
product2.show();
}
}
class Director {
public void Construct(Builder builder) {
builder.BuildPart();
}
}
abstract class Builder {
public abstract void BuildPart();
public abstract Product getResult();
}
class Builder1 extends Builder {
Product product = new Product();
@Override
public void BuildPart() {
product.Add("A");
product.Add("B");
product.Add("C");
product.Add("D");
product.Add("E");
product.Add("F");
}
@Override
public Product getResult() {
return product;
}
}
class Builder2 extends Builder {
Product product = new Product();
@Override
public void BuildPart() {
product.Add("A");
product.Add("B");
product.Add("C");
}
@Override
public Product getResult() {
return product;
}
}
class Product {
List<String> parts = new ArrayList<String>();
public void Add(String part) {
parts.add(part);
}
public void show() {
System.out.print("产品的组成:");
for (String s : parts)
System.out.print(s + " ");
System.out.print("\n");
}
}
3.工厂方法模式(FactoryMethod)
public class FactoryMethod {
public static void main(String[] args) {
Factory factoryA = new FactoryA();
// 父类 对象名 = new 子类();
Product productA = factoryA.createProduct();
// Product productA = new ProductA();
productA.info();
Factory factoryB = new FactoryB();
Product productB = factoryB.createProduct();
productB.info();
}
}
// class Factory
interface Factory {
public Product createProduct();
}
class FactoryA implements Factory {
@Override
public Product createProduct() {
return new ProductA();
}
}
class FactoryB implements Factory {
@Override
public Product createProduct() {
return new ProductB();
}
}
// abstract class Product
interface Product {
// public abstract void info();
public void info();
}
// class ProductA extends Product
class ProductA implements Product {
@Override
public void info() {
System.out.println("产品的信息:A");
}
}
// class ProductB extends Product
class ProductB implements Product {
@Override
public void info() {
System.out.println("产品的信息:B");
}
}
4.原型模式(Prototype)
public class Main {
public static void main(String[] args) {
Product product1 = new Product(2022, 5.28);
System.out.println(product1.getId() + " " + product1.getPrice());
// Product product2 = new Product(2022, 5.28);
Product product2 = (Product) product1.Clone();
System.out.println(product2.getId() + " " + product2.getPrice());
Product product3 = (Product) product1.Clone();
System.out.println(product3.getId() + " " + product3.getPrice());
}
}
interface Prototype {
public Object Clone();
}
class Product implements Prototype {
private int id;
private double price;
public Product() {}
public Product(int id, double price) {
this.id = id;
this.price = price;
}
public int getId() {
return id;
}
public double getPrice() {
return price;
}
@Override
public Object Clone() {
Product object = new Product();
object.id = this.id;
object.price = this.price;
return object;
}
}
5.单例模式(Singleton)
public class SingletonPattern {
public static void main(String[] args) {
// Singleton singleton1 = new Singleton();
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
Singleton singleton3 = Singleton.getInstance();
System.out.println(singleton1.getNumber() + " " + singleton2.getNumber() + " " + singleton3.getNumber());
singleton1.setNumber(528);
System.out.println(singleton1.getNumber() + " " + singleton2.getNumber() + " " + singleton3.getNumber());
}
}
class Singleton {
private int number = 2022;
public void setNumber(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
结构型模式
1.适配器模式(Adapter)
public class AdapterPattern {
public static void main(String[] args) {
USB usb = new Adapter();
usb.Request();
}
}
class USB {
public void Request() {
System.out.println("USB数据线");
}
}
class Adapter extends USB {
private TypeC typeC = new TypeC();
@Override
public void Request() {
typeC.SpecificRequest();
}
}
class TypeC {
public void SpecificRequest() {
System.out.println("Type-C数据线");
}
}
2.桥接模式(Bridge)
public class BridgePattern {
public static void main(String[] args) {
Product productA1 = new ProductA();
Product productA2 = new ProductA();
Color red = new Red();
productA1.setName("产品A1");
productA1.setColor(red);
productA1.Operation();
Blue blue = new Blue();
productA2.setName("产品A2");
productA2.setColor(blue);
productA2.Operation();
}
}
abstract class Product {
private String name;
protected Color color;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setColor(Color color) {
this.color = color;
}
public abstract void Operation();
}
class ProductA extends Product {
@Override
public void Operation() {
color.OperationImp(this.getName());
}
}
interface Color {
public void OperationImp(String name);
}
class Red implements Color {
@Override
public void OperationImp(String name) {
System.out.println(name + ":红色");
}
}
class Blue implements Color {
@Override
public void OperationImp(String name) {
System.out.println(name + ":蓝色");
}
}
3.组合模式(Composite)
import java.util.*;
public class CompositePattern {
public static void main(String[] args) {
// 父类名 对象名 = new 子类名();
AbstractFile root = new Folder("root");
AbstractFile folderA = new Folder("folderA");
AbstractFile folderB = new Folder("folderB");
AbstractFile fileC = new File("fileC");
AbstractFile fileD = new File("fileD");
AbstractFile fileE = new File("fileE");
root.Add(folderA);
root.Add(folderB);
root.Add(fileC);
folderA.Add(fileD);
folderA.Add(fileE);
print(root);
}
static void print(AbstractFile file) {
file.printName();
List<AbstractFile> childrenList = file.getChildren();
if (childrenList == null) return;
// for (对象类型 对象名 : 遍历对象)
for (AbstractFile children : childrenList) {
// children.printName();
print(children);
}
}
}
abstract class AbstractFile {
protected String name;
public void printName() {
System.out.println(name);
}
public abstract boolean Add(AbstractFile file);
public abstract boolean Remove(AbstractFile file);
public abstract List<AbstractFile> getChildren();
}
class Folder extends AbstractFile {
private List<AbstractFile> childrenList = new ArrayList<AbstractFile>();
public Folder(String name) {
this.name = name;
}
@Override
public boolean Add(AbstractFile file) {
return childrenList.add(file);
}
@Override
public boolean Remove(AbstractFile file) {
return childrenList.remove(file);
}
@Override
public List<AbstractFile> getChildren() {
return childrenList;
}
}
class File extends AbstractFile {
public File(String name) {
this.name = name;
}
@Override
public boolean Add(AbstractFile file) {
return false;
}
@Override
public boolean Remove(AbstractFile file) {
return false;
}
@Override
public List<AbstractFile> getChildren() {
return null;
}
}
4.装饰器模式(Decorator)
public class DecoratorPattern {
public static void main(String[] args) {
Person zhangsan = new Student("张三");
zhangsan = new DecoratorA(zhangsan);
zhangsan = new DecoratorB(zhangsan);
zhangsan.Operation();
System.out.println("\n=====我是分割线=====");
// 对象链
Person lisi = new DecoratorB(new DecoratorA(new Student("李四")));
}
}
abstract class Decorator extends Person {
protected Person person;
}
class DecoratorA extends Decorator {
public DecoratorA(Person person) {
this.person = person;
}
@Override
public void Operation() { // 职责
person.Operation(); // 原本的职责
System.out.print("写作业 ");
}
}
class DecoratorB extends Decorator {
public DecoratorB(Person person) {
this.person = person;
}
@Override
public void Operation() { // 职责
person.Operation(); // 原本的职责
System.out.print("考试 ");
}
}
abstract class Person {
protected String name;
public abstract void Operation(); // 职责
}
class Student extends Person {
public Student(String name) {
this.name = name;
}
@Override
public void Operation() {
System.out.print(name + "的职责:学习 ");
}
}
5.外观模式(Facade)
public class FacadePattern {
public static void main(String[] args) {
Facade facade = new Facade();
facade.methodA();
facade.methodB();
facade.methodC();
}
}
class Facade {
SubSystemOne subSystemOne;
SubSystemTwo subSystemTwo;
SubSystemThree subSystemThree;
public Facade() {
subSystemOne = new SubSystemOne();
subSystemTwo = new SubSystemTwo();
subSystemThree = new SubSystemThree();
}
public void methodA() {
subSystemOne.methodOne();
}
public void methodB() {
subSystemTwo.methodTwo();
}
public void methodC() {
subSystemThree.methodThree();
}
}
class SubSystemOne {
public void methodOne() {
System.out.println("执行子系统一的功能");
}
}
class SubSystemTwo {
public void methodTwo() {
System.out.println("执行子系统二的功能");
}
}
class SubSystemThree {
public void methodThree() {
System.out.println("执行子系统三的功能");
}
}
6.享元模式(Flyweight)
import java.util.*;
public class FlyWeightPattern {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Random random = new Random();
String[] colors = {"red", "blue", "green", "white", "black"};
for (int i = 1; i <= 100; i ++ ) {
int x = random.nextInt(colors.length); // [0 ~ 4]
Shape shape = factory.getShape(colors[x]);
System.out.print("第" + i + "个圆:");
shape.draw(random.nextInt(2022), random.nextInt(528));
}
}
}
class ShapeFactory {
private Map<String, Shape> map = new HashMap<String, Shape>();
public Shape getShape(String key) {
if (!map.containsKey(key)) {
map.put(key, new Circle(key));
System.out.println("create color:" + key + " circle");
}
return map.get(key);
}
}
abstract class Shape {
protected String color;
public abstract void draw(int x, int y);
}
class Circle extends Shape {
public Circle(String color) {
this.color = color;
}
@Override
public void draw(int x, int y) {
System.out.println("draw a color:" + color + " circle x:" + x + " y:" + y);
}
}
7.代理模式(Proxy)
public class ProxyPattern {
public static void main(String[] args) {
RealSubject realSubject = new RealSubject();
Proxy proxy = new Proxy(realSubject);
proxy.buy();
}
}
interface Subject {
public void buy();
}
class Proxy implements Subject {
protected RealSubject realSubject;
public Proxy(RealSubject realSubject) {
this.realSubject = realSubject;
}
@Override
public void buy() {
System.out.println("办理购买前的手续");
realSubject.buy(); // 付钱
System.out.println("办理购买后的手续");
}
}
class RealSubject implements Subject {
@Override
public void buy() {
System.out.println("付钱");
}
}
行为型模式
1.责任链模式(Chain of Responsibility)
public class ChainOfResponsibilityPattern {
public static void main(String[] args) {
Handler fudaoyuan = new FuDaoYuan();
Handler yuanzhang = new YuanZhang();
Handler xiaozhang = new XiaoZhang();
fudaoyuan.setNext(yuanzhang);
yuanzhang.setNext(xiaozhang);
fudaoyuan.HandlerRequest(31);
}
}
abstract class Handler {
protected Handler next;
public void setNext(Handler next) {
this.next = next;
}
public abstract void HandlerRequest(int request);
}
class FuDaoYuan extends Handler { // <= 7 审批
@Override
public void HandlerRequest(int request) {
if (request <= 7) {
System.out.println("辅导员审批通过");
} else {
if (next != null) {
next.HandlerRequest(request);
} else {
System.out.println("无法审批");
}
}
}
}
class YuanZhang extends Handler { // <= 15 审批
@Override
public void HandlerRequest(int request) {
if (request <= 15) {
System.out.println("院长审批通过");
} else {
if (next != null) {
next.HandlerRequest(request);
} else {
System.out.println("无法审批");
}
}
}
}
class XiaoZhang extends Handler { // <= 30 审批
@Override
public void HandlerRequest(int request) {
if (request <= 30) {
System.out.println("校长审批通过");
} else {
if (next != null) {
next.HandlerRequest(request);
} else {
System.out.println("无法审批");
}
}
}
}
2.命令模式(Command)
public class CommandPattern {
public static void main(String[] args) {
Tv tv = new Tv(); // 接收者 对象 电视机
Command onCommand = new OnCommand(tv); // 命令对象 开机命令
Command offCommand = new OffCommand(tv); // 命令对象 关机命令
Invoker invoker = new Invoker(); // 请求者
invoker.setCommand(onCommand); // 给请求者设置 开机 命令
invoker.call(); // 请求者去请求命令
System.out.println("========================================");
invoker.setCommand(offCommand); // 给请求者设置 关机命令
invoker.call(); // 请求者去请求命令
}
}
class Invoker { // 请求者
private Command command; // 命令
public void setCommand(Command command) { // 设置请求者 的 请求的命令
this.command = command;
}
public void call() { // 调用
command.Execute();
}
}
interface Command { // 命令接口
public void Execute(); // 执行命令
}
class OnCommand implements Command { // 开机命令
private Tv tv;
public OnCommand(Tv tv) {
this.tv = tv;
}
@Override
public void Execute() {
tv.OnAction();
}
}
class OffCommand implements Command { // 关机命令
private Tv tv;
public OffCommand(Tv tv) {
this.tv = tv;
}
@Override
public void Execute() {
tv.OffAction();
}
}
class Tv { // 接收者 电视机
public void OnAction() { // 开机行为
System.out.println("电视机开机了...");
}
public void OffAction() { // 关机行为
System.out.println("电视机关机了...");
}
}
3.解释器模式(Interpreter)
import java.util.*;
public class InterpreterPattern {
public static void main(String[] args) {
Context context = new Context();
context.check("A区的开发人员");
context.check("B区的调试人员");
context.check("C区的测试人员");
System.out.println("==========");
context.check("D区的程序员");
context.check("D区的测试员");
context.check("A区的程序员");
}
}
class Context {
private String[] regions = {"A区", "B区", "C区"};
private String[] persons = {"开发人员", "测试人员", "调试人员"};
private NonterminalExprssion nonterminal;
public Context() {
TerminalExpression region = new TerminalExpression(regions);
TerminalExpression person = new TerminalExpression(persons);
nonterminal = new NonterminalExprssion(region, person);
}
public void check(String info) {
boolean bool = nonterminal.Interpret(info);
if (bool) {
System.out.println("识别成功");
} else {
System.out.println("识别失败");
}
}
}
interface Expression {
public boolean Interpret(String info);
}
class NonterminalExprssion implements Expression {
private TerminalExpression region;
private TerminalExpression person;
public NonterminalExprssion(TerminalExpression region, TerminalExpression person) {
this.region = region;
this.person = person;
}
@Override
public boolean Interpret(String info) {
String[] str = info.split("的");
// B区的调试人员 --> str = {"B区", "调试人员"}
return region.Interpret(str[0]) && person.Interpret(str[1]);
}
}
class TerminalExpression implements Expression {
private Set<String> set = new HashSet<>();
public TerminalExpression(String[] data) {
// for (遍历对象类型 对象名 : 遍历对象)
for (String str : data) {
set.add(str);
}
}
@Override
public boolean Interpret(String info) {
return set.contains(info);
}
}
4.迭代器模式(Iterator)
import java.util.*;
public class IteratorPattern {
public static void main(String[] args) {
BookAggregate bookAggregate = new BookAggregate();
String[] books = {"数据结构", "操作系统", "计算机网络", "计算机组成原理"};
double[] prices = {10.24, 20.48, 40.96, 81.92};
for (int i = 0; i < 4; i ++ ) {
bookAggregate.Add(new Book(books[i], prices[i]));
}
Iterator bookIterator = bookAggregate.CreateIterator();
while (bookIterator.hasNext()) {
Book book = (Book) bookIterator.next();
System.out.println(book.getName() + " " + book.getPrice());
}
}
}
interface Iterator {
public boolean hasNext();
public Object next();
}
class BookIterator implements Iterator {
private int index;
private BookAggregate bookAggregate;
public BookIterator(BookAggregate bookAggregate) {
this.index = 0;
this.bookAggregate = bookAggregate;
}
@Override
public boolean hasNext() {
if (index < bookAggregate.getSize()) {
return true;
} else {
return false;
}
}
@Override
public Object next() {
Object obj = bookAggregate.get(index);
index ++ ;
return obj;
}
}
interface Aggregate {
public Iterator CreateIterator();
}
class BookAggregate implements Aggregate {
private List<Book> list = new ArrayList<Book>();
public void Add(Book book) {
list.add(book);
}
public Book get(int index) {
return list.get(index);
}
public int getSize() {
return list.size();
}
@Override
public Iterator CreateIterator() {
return new BookIterator(this);
}
}
class Book {
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
5.中介者(Mediator)
public class MediatorPattern {
public static void main(String[] args) {
ConcreteMediator mediator = new ConcreteMediator();
Colleague1 colleague1 = new Colleague1(mediator);
Colleague2 colleague2 = new Colleague2(mediator);
mediator.setColleague1(colleague1);
mediator.setColleague2(colleague2);
colleague1.sendMessage("软考加油");
colleague2.sendMessage("祝大家软考顺利通过!");
}
}
abstract class Colleague {
protected Mediator mediator;
}
class Colleague1 extends Colleague {
public Colleague1(Mediator mediator) {
this.mediator = mediator;
}
public void sendMessage(String message) {
mediator.sendMessage(message, this);
}
public void Notify(String message) {
System.out.println("同事1收到消息:" + message);
}
}
class Colleague2 extends Colleague {
public Colleague2(Mediator mediator) {
this.mediator = mediator;
}
public void sendMessage(String message) {
mediator.sendMessage(message, this);
}
public void Notify(String message) {
System.out.println("同事2收到消息:" + message);
}
}
abstract class Mediator {
public abstract void sendMessage(String message, Colleague colleague);
}
class ConcreteMediator extends Mediator {
private Colleague1 colleague1;
private Colleague2 colleague2;
public void setColleague1(Colleague1 colleague1) {
this.colleague1 = colleague1;
}
public void setColleague2(Colleague2 colleague2) {
this.colleague2 = colleague2;
}
public void sendMessage(String message, Colleague colleague) {
if (colleague == colleague1) {
colleague2.Notify(message); // 让同事2收到消息
} else {
colleague1.Notify(message); // 让同事1收到消息
}
}
}
6.备忘录模式(Memento)
import java.util.*;
public class MementoPattern {
public static void main(String[] args) {
Caretaker caretaker = new Caretaker();
Originator originator = new Originator();
originator.setState("1024");
Memento backup1 = originator.createMemento();
caretaker.addMemento(backup1);
originator.setState("2048");
Memento backup2 = originator.createMemento();
caretaker.addMemento(backup2);
originator.setState("4096");
Memento backup3 = originator.createMemento();
caretaker.addMemento(backup3);
System.out.println(originator.getState());
caretaker.showMemento();
Memento memento1 = caretaker.getMemento(2);
originator.setMemento(memento1);
System.out.println("根据第2次备份还原之后的状态为:" + originator.getState());
}
}
class Originator { // 原发器
private String state;
public void setState(String state) {
this.state = state;
}
public String getState() {
return state;
}
public Memento createMemento() {
return new Memento(state);
}
public void setMemento(Memento memento) {
state = memento.getState();
}
}
class Memento { // 备忘录
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
class Caretaker { // 管理者
private List<Memento> mementoList = new ArrayList<>();
public void addMemento(Memento memento) {
mementoList.add(memento);
}
public Memento getMemento(int index) {
// 判断参数是否合法
if (index >= 1 && index <= mementoList.size()) {
return mementoList.get(index - 1);
}
return null;
}
public void showMemento() {
int cnt = 1;
// for (遍历对象类型 对象名 : 遍历对象)
for (Memento memento : mementoList) {
System.out.println("第" + cnt + "次备份,状态为:" + memento.getState());
cnt ++ ;
}
}
}
7.观察者模式(Observer)
import java.util.*;
public class ObserverPattern {
public static void main(String[] args) {
Subject subjectA = new ConcreteSubject("目标A");
Observer observerB = new ConcreteObserver("张三", subjectA);
Observer observerC = new ConcreteObserver("李四", subjectA);
Observer observerD = new ConcreteObserver("王五", subjectA);
subjectA.setState("更新了");
System.out.println("======================================");
subjectA.Detach(observerD);
subjectA.setState("停更了");
}
}
interface Subject { // 目标
public void Attach(Observer observer); // 添加观察者
public void Detach(Observer observer); // 删除观察者
public void Notify(); // 状态改变后 通知所有观察者
public void setState(String state); // 设置状态(改变状态)
public String getState(); // 获取状态
}
class ConcreteSubject implements Subject {
private String name;
private String state;
private List<Observer> observerList;
public ConcreteSubject(String name) {
state = "未更新";
this.name = name;
observerList = new ArrayList<Observer>();
}
public void setState(String state) {
this.state = state;
System.out.println(name + "的状态发生变化,变化后的状态为:" + state);
Notify();
}
public String getState() {
return state;
}
public void Attach(Observer observer) {
observerList.add(observer);
}
public void Detach(Observer observer) {
observerList.remove(observer);
}
public void Notify() {
// for (遍历对象类型 对象名 : 遍历对象)
for (Observer observer : observerList) {
observer.update();
}
}
}
interface Observer { // 观察者接口
public void update(); // 收到通知 更新观察者的状态
}
class ConcreteObserver implements Observer {
private String name;
private String state;
private Subject subject;
public ConcreteObserver(String name, Subject subject) {
this.name = name;
this.subject = subject;
subject.Attach(this);
state = subject.getState();
}
@Override
public void update() {
System.out.println(name + "收到通知");
state = subject.getState(); // 让当前观察者的状态 和 改变了状态之后的目标的状态保持一致
System.out.println(name + "改变后的状态为:" + state);
}
}
8.状态模式(State)
public class StatePattern {
public static void main(String[] args) {
Context context = new Context(); // count:3
System.out.println(context.getState());
context.Request(); // 购买一个饮料 count = 2
context.Request(); // 购买一个饮料 count = 1
context.Request(); // 购买一个饮料 count = 0
System.out.println(context.getState());
context.Request(); // 无货 等待补货 补货成功 count = 5
System.out.println(context.getState());
context.Request(); // 购买一个饮料 count = 4
System.out.println(context.getCount());
}
}
class Context { // 贩卖机
private int count;
private State state;
public Context() {
count = 3;
state = new StateA();
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public void Request() { // 购买一个饮料
state.Handle(this);
}
}
interface State {
public void Handle(Context context);
}
class StateA implements State { // 有货
@Override
public void Handle(Context context) {
int count = context.getCount();
if (count >= 1) {
System.out.println("购买成功!");
context.setCount(count - 1);
if (context.getCount() == 0) {
context.setState(new StateB());
}
} else {
System.out.println("购买失败!");
}
}
}
class StateB implements State { // 无货
@Override
public void Handle(Context context) {
int count = context.getCount();
if (count == 0) {
System.out.println("购买失败!等待补货");
context.setCount(5);
System.out.println("补货成功,请重新购买");
context.setState(new StateA());
}
}
}
9.策略模式(Strategy)
public class StrategyPattern {
public static void main(String[] args) {
Strategy add = new AddStrategy();
Strategy subtraction = new SubtractionStrategy();
Strategy multiply = new MultiplyStrategy();
OperationContext context = new OperationContext(add);
context.Operation(2022, 528);
context = new OperationContext(subtraction);
context.Operation(2022, 528);
context = new OperationContext(multiply);
context.Operation(2022, 528);
}
}
class OperationContext {
private Strategy strategy;
public OperationContext(Strategy strategy) {
this.strategy = strategy;
}
public void Operation(int a, int b) {
strategy.TwoNumberOperation(a, b);
}
}
interface Strategy {
public void TwoNumberOperation(int a, int b);
}
class AddStrategy implements Strategy {
@Override
public void TwoNumberOperation(int a, int b) {
System.out.println(a + b);
}
}
class SubtractionStrategy implements Strategy {
@Override
public void TwoNumberOperation(int a, int b) {
System.out.println(a - b);
}
}
class MultiplyStrategy implements Strategy {
@Override
public void TwoNumberOperation(int a, int b) {
System.out.println(a * b);
}
}
10.模板方法模式(TemplateMethod)
public class TemplateMethodPattern {
public static void main(String[] args) {
// 父类名 对象名 = new 子类名();
Person student = new Student();
Person teacher = new Teacher();
student.TemplateMethod();
System.out.println("=====我是分割线=====");
teacher.TemplateMethod();
}
}
abstract class Person {
public void TemplateMethod() {
System.out.println("上课 去教室"); // 1
PrimitiveOperation1(); // 2
System.out.println("下课 离开教室"); // 3
PrimitiveOperation2(); // 4
}
public abstract void PrimitiveOperation1(); // 原语操作 1 :上课过程 学生 听课…… 老师 讲课
public abstract void PrimitiveOperation2(); // 原语操作 2 :作业 学生 写作业 提交作业…… 老师 批改作业 打分数
}
class Student extends Person {
@Override
public void PrimitiveOperation1() {
System.out.println("学生:听课 学习 做笔记 提出问题");
}
@Override
public void PrimitiveOperation2() {
System.out.println("学生:写作业 提交作业");
}
}
class Teacher extends Person {
@Override
public void PrimitiveOperation1() {
System.out.println("老师:上课 讲课 解答问题 布置作业");
}
@Override
public void PrimitiveOperation2() {
System.out.println("老师:批改作业 打分数");
}
}
11.访问者模式(Visitor)
public class TemplateMethodPattern {
public static void main(String[] args) {
// 父类名 对象名 = new 子类名();
Person student = new Student();
Person teacher = new Teacher();
student.TemplateMethod();
System.out.println("=====我是分割线=====");
teacher.TemplateMethod();
}
}
abstract class Person {
public void TemplateMethod() {
System.out.println("上课 去教室"); // 1
PrimitiveOperation1(); // 2
System.out.println("下课 离开教室"); // 3
PrimitiveOperation2(); // 4
}
public abstract void PrimitiveOperation1(); // 原语操作 1 :上课过程 学生 听课…… 老师 讲课
public abstract void PrimitiveOperation2(); // 原语操作 2 :作业 学生 写作业 提交作业…… 老师 批改作业 打分数
}
class Student extends Person {
@Override
public void PrimitiveOperation1() {
System.out.println("学生:听课 学习 做笔记 提出问题");
}
@Override
public void PrimitiveOperation2() {
System.out.println("学生:写作业 提交作业");
}
}
class Teacher extends Person {
@Override
public void PrimitiveOperation1() {
System.out.println("老师:上课 讲课 解答问题 布置作业");
}
@Override
public void PrimitiveOperation2() {
System.out.println("老师:批改作业 打分数");
}
}