目录
责任链模式
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(5);
}
}
abstract class Handler {
protected Handler next;
public void setNext(Handler next) {
this.next = next;
}
public abstract void HandlerRequest(int request);
}
class FuDaoYuan extends Handler {
@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("无法审批");
}
}
}
}
命令模式
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("电视机关机了...");
}
}
迭代器模式
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;
}
}
中介者模式
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收到消息
}
}
}
备忘录模式
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++;
}
}
}
观察者模式
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;
}
@Override
public void Attach(Observer observer) {
observerList.add(observer);
}
@Override
public void Detach(Observer observer) {
observerList.remove(observer);
}
@Override
public void Notify() {
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);
}
}
状态模式
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());
}
}
}
策略模式
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);
}
}
访问者模式
public class VisitorPattern {
public static void main(String[] args) {
PersonStructure structure = new PersonStructure();
Visitor1 visitor1 = new Visitor1();
System.out.println("访问者1的访问记录:");
structure.Accept(visitor1);
System.out.println("学生年龄的总和:" + visitor1.getStudentAgeSum() + " 老师年龄的总和:" + visitor1.getTeacherAgeSum());
System.out.println("----------------------------------------------");
Visitor2 visitor2 = new Visitor2();
System.out.println("访问者2的访问记录:");
structure.Accept(visitor2);
System.out.println("学生的最高成绩:" + visitor2.getMaxScore() + " 老师的最高工龄:" + visitor2.getMaxWorkYear());
}
}
interface Visitor {
public void visitStudent(Student student); // 访问学生
public void visitTeacher(Teacher teacher); // 访问老师
}
class Visitor1 implements Visitor { // 访问者1 分别统计学生和老师的年龄总和
private int studentAgeSum = 0;
private int teacherAgeSum = 0;
public int getStudentAgeSum() {
return studentAgeSum;
}
public int getTeacherAgeSum() {
return teacherAgeSum;
}
@Override
public void visitStudent(Student student) {
System.out.println("访问者1访问学生:" + student.getName() + " 年龄:" + student.getAge());
studentAgeSum += student.getAge();
}
@Override
public void visitTeacher(Teacher teacher) {
System.out.println("访问者1访问老师:" + teacher.getName() + " 年龄:" + teacher.getAge());
teacherAgeSum += teacher.getAge();
}
}
class Visitor2 implements Visitor { // 访问者2 分别求出 学生的最高成绩 以及 老师的最高工龄
private int maxScore = -1;
private int maxWorkYear = -1;
public int getMaxScore() {
return maxScore;
}
public int getMaxWorkYear() {
return maxWorkYear;
}
@Override
public void visitStudent(Student student) {
System.out.println("访问者2访问学生:" + student.getName() + " 成绩:" + student.getScore());
maxScore = Math.max(maxScore, student.getScore());
}
@Override
public void visitTeacher(Teacher teacher) {
System.out.println("访问者2访问老师:" + teacher.getName() + " 工龄:" + teacher.getWorkYear());
maxWorkYear = Math.max(maxWorkYear, teacher.getWorkYear());
}
}
class PersonStructure {
private List<Person> personList = new ArrayList<Person>();
public PersonStructure() {
personList.add(new Student("张三", 20, 70));
personList.add(new Student("李四", 21, 80));
personList.add(new Student("王五", 22, 90));
personList.add(new Teacher("李老师", 26, 3));
personList.add(new Teacher("陈老师", 27, 4));
personList.add(new Teacher("刘老师", 28, 5));
}
public void Accept(Visitor visitor) {
// for (遍历对象类型 对象名 : 遍历对象)
for (Person person : personList) {
person.Accept(visitor);
}
}
}
abstract class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public abstract void Accept(Visitor visitor);
}
class Student extends Person {
private int score;
public Student(String name, int age, int score) {
super(name, age);
this.score = score;
}
public int getScore() {
return score;
}
@Override
public void Accept(Visitor visitor) {
visitor.visitStudent(this);
}
}
class Teacher extends Person {
private int workYear;
public Teacher(String name, int age, int workYear) {
super(name, age);
this.workYear = workYear;
}
public int getWorkYear() {
return workYear;
}
@Override
public void Accept(Visitor visitor) {
visitor.visitTeacher(this);
}
}
解释器模式
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);
}
}
模版方法模式
package 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("老师:批改作业 打分数");
}
}