public class TemplateMothodCase {
public static void main(String[] args) {
System.out.println("----制作红豆豆浆----");
RedBeanSoyaMilk redBeanSoyaMilk = new RedBeanSoyaMilk();
redBeanSoyaMilk.make();
System.out.println("----制作花生豆浆----");
PeanutSoyaMilk peanutSoyaMilk = new PeanutSoyaMilk();
peanutSoyaMilk.make();
}
}
/**
* 抽象类:豆浆
*/
abstract class SoyaMilk {
/**
* 模板方法make:模板方法可以做成 final, 不让子类去覆盖
*/
final void make() {
select();
addCondiments();
soak();
beat();
}
/**
* 选材料
*/
void select() {
System.out.println("第一步:选择好的新鲜黄豆");
}
/**
* 添加不同的配料,抽象方法交给子类具体实现
*/
abstract void addCondiments();
/**
* 浸泡
*/
void soak() {
System.out.println("第三步:黄豆和配料开始浸泡,需要3小时");
}
void beat() {
System.out.println("第四步:黄豆和配料放到豆浆机打碎");
}
}
/**
* 具体的子类
*/
class RedBeanSoyaMilk extends SoyaMilk {
@Override
void addCondiments() {
System.out.println("加入上好的红豆");
}
}
class PeanutSoyaMilk extends SoyaMilk {
@Override
void addCondiments() {
System.out.println("加入上好的花生");
}
}
abstract class SoyaMilk {
/**
* 模板方法make:模板方法可以做成 final, 不让子类去覆盖
*/
final void make() {
select();
if (customerWantCondiments()) {
addCondiments();
}
soak();
beat();
}
// 省略其它...
/**
* 钩子方法,决定是否需要添加配料
*/
boolean customerWantCondiments() {
return true;
}
}
/**
* 纯豆浆
*/
class PureSoyaMilk extends SoyaMilk {
@Override
void addCondiments() {
// 空实现
}
@Override
boolean customerWantCondiments() {
return false;
}
}
/**
* 完成IoC容器的创建及初始化工作
*/
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// STEP 1: 刷新预处理
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// STEP 2:
// a) 创建IoC容器(DefaultListableBeanFactory)
// b) 加载解析XML文件(最终存储到Document对象中)
// c) 读取Document对象,并完成BeanDefinition的加载和注册工作
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// STEP 3: 对IoC容器进行一些预处理(设置一些公共属性)
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// STEP 4:
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// STEP 5: 调用BeanFactoryPostProcessor后置处理器对BeanDefinition处理
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// STEP 6: 注册BeanPostProcessor后置处理器
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// STEP 7: 初始化一些消息源(比如处理国际化的i18n等消息源)
initMessageSource();
// Initialize event multicaster for this context.
// STEP 8: 初始化应用事件广播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// STEP 9: 初始化一些特殊的bean,是一个钩子方法
onRefresh();
// Check for listener beans and register them.
// STEP 10: 注册一些监听器
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// STEP 11: 实例化剩余的单例bean(非懒加载方式)
// 注意事项:Bean的IoC、DI和AOP都是发生在此步骤
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// STEP 12: 完成刷新时,需要发布对应的事件
finishRefresh();
}
// 省略...
}
}
↓↓↓↓↓
// 也用到了模板方法模式
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 主要是通过该方法完成IoC容器的刷新
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
↓↓↓↓↓
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
@Override
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
public class CommandCase {
public static void main(String[] args) {
// 创建点灯对象(接收者)
LightReceiver receiver = new LightReceiver();
// 创建点灯相关的开关命令
LightOnCommand lightOnCommand = new LightOnCommand(receiver);
LightOffCommand lightOffCommand = new LightOffCommand(receiver);
// 创建一个遥控器
RemoteController remoteController = new RemoteController();
// 给遥控器设置命令
remoteController.setCommand(0, lightOnCommand, lightOffCommand);
System.out.println("测试遥控器");
System.out.println("--------按下灯的开按钮--------");
remoteController.onButtonWasPushed(0);
System.out.println("--------按下灯的关按钮--------");
remoteController.offButtonWasPushed(0);
System.out.println("--------按下撤销按钮--------");
remoteController.undoButtonWasPushed();
}
}
/**
* 命令接口
*/
interface Command {
void execute();
void undo();
}
/**
* 命令接收者
*/
class LightReceiver {
public void on() {
System.out.println("点灯打开了...");
}
public void off() {
System.out.println("点灯关闭了...");
}
}
/**
* 具体命令
*/
class LightOnCommand implements Command {
/**
* 聚合点灯命令接收者
*/
private LightReceiver receiver;
LightOnCommand(LightReceiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.on();
}
@Override
public void undo() {
receiver.off();
}
}
class LightOffCommand implements Command {
/**
* 聚合点灯命令接收者
*/
private LightReceiver receiver;
LightOffCommand(LightReceiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.off();
}
@Override
public void undo() {
receiver.on();
}
}
/**
* 空命令:用于初始化每个按钮,当调用空命令时,对象什么都不做
* 其实这也是一种设计模式,可以省掉对空的判断
*/
class NoCommand implements Command {
@Override
public void execute() { }
@Override
public void undo() { }
}
/**
* 命令的调用者/发布者:遥控器
*/
class RemoteController {
private Command[] onCommands;
private Command[] offCommands;
/**
* 撤销命令
*/
private Command undoCommand;
RemoteController() {
onCommands = initCommand(5);
offCommands = initCommand(5);
}
private Command[] initCommand(int num) {
Command[] commands = new Command[num];
for (int i = 0; i < num; i++) {
commands[i] = new NoCommand();
}
return commands;
}
/**
* 给遥控器按钮设置需要的命令
*/
public void setCommand(int no, Command onCommand, Command offCommand) {
onCommands[no] = onCommand;
offCommands[no] = offCommand;
}
/**
* 按下开按钮
*/
public void onButtonWasPushed(int no) {
// 找到你按下的 开 的按钮,并调用对应的方法
onCommands[no].execute();
// 记录这次操作,用于撤销
undoCommand = onCommands[no];
}
/**
* 按下关按钮
*/
public void offButtonWasPushed(int no) {
// 找到你按下的 关 的按钮,并调用对应的方法
offCommands[no].execute();
// 记录这次操作,用于撤销
undoCommand = offCommands[no];
}
/**
* 按下撤销按钮
*/
public void undoButtonWasPushed() {
undoCommand.undo();
}
}
//测试遥控器
//--------按下灯的开按钮--------
//点灯打开了
//--------按下灯的关按钮--------
//点灯关闭了
//--------按下撤销按钮--------
//点灯打开了
@FunctionalInterface
public interface StatementCallback<T> {
@Nullable
T doInStatement(Statement stmt) throws SQLException, DataAccessException;
}
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
@Override
public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException {
return result(query(sql, new RowMapperResultSetExtractor<>(rowMapper)));
}
↓↓↓↓↓
@Override
@Nullable
public <T> T query(final String sql, final ResultSetExtractor<T> rse) throws DataAccessException {
Assert.notNull(sql, "SQL must not be null");
Assert.notNull(rse, "ResultSetExtractor must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL query [" + sql + "]");
}
class QueryStatementCallback implements StatementCallback<T>, SqlProvider {
@Override
@Nullable
// !!!!!!!核心
public T doInStatement(Statement stmt) throws SQLException {
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
return rse.extractData(rs);
}
finally {
JdbcUtils.closeResultSet(rs);
}
}
@Override
public String getSql() {
return sql;
}
}
// !!!!!!!核心
return execute(new QueryStatementCallback());
}
↓↓↓↓↓
@Override
@Nullable
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
stmt = con.createStatement();
applyStatementSettings(stmt);
// !!!!核心
T result = action.doInStatement(stmt);
handleWarnings(stmt);
return result;
}
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("StatementCallback", sql, ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
}
public class VisitorCase {
public static void main(String[] args) {
// 创建数据结构
ObjectStructure structure = new ObjectStructure();
structure.attach(new Male("Tom"));
structure.attach(new Male("Jack"));
structure.attach(new Male("Smith"));
structure.attach(new Female("Lily"));
structure.attach(new Female("Sari"));
// 成功
Succcess succcess = new Succcess();
structure.display(succcess);
// 失败
Fail fail = new Fail();
structure.display(fail);
}
}
/**
* 抽象访问者:测评的动作
*/
abstract class Action {
abstract void getMaleResult(Male male);
abstract void getFemaleResult(Female female);
}
/**
* 具体访问者
*/
class Succcess extends Action {
@Override
void getMaleResult(Male male) {
System.out.println(male.name + ": Yes");
}
@Override
void getFemaleResult(Female female) {
System.out.println(female.name + ": Yes");
}
}
class Fail extends Action {
@Override
void getMaleResult(Male male) {
System.out.println(male.name + ": No");
}
@Override
void getFemaleResult(Female female) {
System.out.println(female.name + ": No");
}
}
/**
* 抽象元素:人
*/
abstract class Person {
public String name;
Person(String name) {
this.name = name;
}
abstract void accept(Action action);
}
/**
* 具体的元素:男人和女人
* 合理我们使用到了双分派,即首先在客户端程序中,将具体状态作为参数传递到了【Male、Female】中
* 然后【Male、Female】类调用作为参数的"具体方法"中getXxxResult,同时将自己(this)作为参数传入,即第二次分派
*/
class Male extends Person {
Male(String name) {
super("[M]" + name);
}
@Override
void accept(Action action) {
action.getMaleResult(this);
}
}
class Female extends Person {
Female(String name) {
super("[F]" + name);
}
@Override
void accept(Action action) {
action.getFemaleResult(this);
}
}
/**
* 数据结构:管理了很多人(Male、Female)
*/
class ObjectStructure {
/**
* 维护了一个集合
*/
private List<Person> persons = new LinkedList<>();
/**
* 增加
*/
public void attach(Person p) {
persons.add(p);
}
/**
* 移除
*/
public void detach(Person p) {
persons.remove(p);
}
/**
* 显示
*/
public void display(Action action) {
for (Person p : persons) {
p.accept(action);
}
}
}
public class IteratorCase {
public static void main(String[] args) {
ComputerCollege computerCollege = new ComputerCollege();
computerCollege.addDepartment("Java专业", "学习Java");
computerCollege.addDepartment("Php专业", "学习Php");
computerCollege.addDepartment("大数据专业", "学习大数据");
InfoCollege infoCollege = new InfoCollege();
infoCollege.addDepartment("信息安全专业", "学习信息安全");
infoCollege.addDepartment("网络安全专业", "学习网络安全");
List<College> colleges = new ArrayList<>();
colleges.add(computerCollege);
colleges.add(infoCollege);
OutputImpl output = new OutputImpl(colleges);
output.printCollege();
}
}
/**
* 系
*/
@Data
@AllArgsConstructor
class Department {
private String name;
private String desc;
}
/**
* 计算机学院迭代器
*/
class ComputerCollegeIterator implements Iterator<Department> {
/**
* 这里我们定义 Department 是以数组形式存放
*/
private Department[] departments;
/**
* 遍历的位置
*/
private int position;
ComputerCollegeIterator(Department[] departments) {
this.departments = departments;
}
@Override
public boolean hasNext() {
return position < departments.length && departments[position] != null;
}
@Override
public Department next() {
Department department = departments[position];
position += 1;
return department;
}
@Override
public void remove() {
}
}
/**
* 信息工程学院迭代器
*/
class InfoCollegeIterator implements Iterator<Department> {
/**
* 这里我们定义 Department 是以List集合形式存放
*/
private List<Department> departments;
/**
* 遍历的索引位置
*/
private int index = -1;
InfoCollegeIterator(List<Department> departments) {
this.departments = departments;
}
@Override
public boolean hasNext() {
if (index >= departments.size() - 1) {
return false;
} else {
index += 1;
return true;
}
}
@Override
public Department next() {
return departments.get(index);
}
@Override
public void remove() {
}
}
/**
* 聚合接口:学院
*/
interface College {
String getName();
void addDepartment(String name, String desc);
Iterator<Department> createIterator();
}
/**
* 计算机学院
*/
class ComputerCollege implements College {
private Department[] departments;
/**
* 保存当前数组对象的个数
*/
private int numOfDep;
ComputerCollege() {
departments = new Department[5];
}
@Override
public String getName() {
return "计算机学院";
}
@Override
public void addDepartment(String name, String desc) {
departments[numOfDep++] = new Department(name, desc);
}
@Override
public Iterator<Department> createIterator() {
return new ComputerCollegeIterator(departments);
}
}
/**
* 信息工程学院
*/
class InfoCollege implements College {
private List<Department> departments;
InfoCollege() {
departments = new ArrayList<>();
}
@Override
public String getName() {
return "信息工程学院";
}
@Override
public void addDepartment(String name, String desc) {
departments.add(new Department(name, desc));
}
@Override
public Iterator<Department> createIterator() {
return new InfoCollegeIterator(departments);
}
}
/**
* 输出
*/
class OutputImpl {
/**
* 学院集合
*/
private List<College> colleges;
OutputImpl(List<College> colleges) {
this.colleges = colleges;
}
/**
* 遍历所有学院,调用 printDepartment
*/
public void printCollege() {
Iterator<College> iterator = colleges.iterator();
while (iterator.hasNext()) {
College college = iterator.next();
System.out.println("----" + college.getName() + "----");
printDepartment(college.createIterator());
}
}
private void printDepartment(Iterator<Department> iterator) {
while (iterator.hasNext()) {
Department department = iterator.next();
System.out.println(department.getName());
}
}
}
public class JDKIterator {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("jack");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
public class ObserverCase {
public static void main(String[] args) {
// 创建接入方 currentConditions
CurrentConditions conditions = new CurrentConditions();
// 创建 WeatherData 并将 接入方 currentConditions 传递到 WeatherData 中
WeatherData weatherData = new WeatherData(conditions);
// 更新天气情况
weatherData.setData(30, 150, 40);
//天气情况变化
System.out.println("============天气情况变化=============");
weatherData.setData(40, 160, 20);
}
}
/**
* 显示当前天气情况(可以理解成是气象站自己的网站)
*/
class CurrentConditions {
/**
* 温度、气压、湿度
*/
private float temperature;
private float pressure;
private float humidity;
/**
* 更新 天气情况,是由 WeatherData 来调用 ==>> 使用推送模式
*/
public void update(float temperature, float pressure, float humidity) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
display();
}
/**
* 显示
*/
private void display() {
System.out.println("***Today temperature: " + temperature + "***");
System.out.println("***Today pressure: " + pressure + "***");
System.out.println("***Today humidity: " + humidity + "***");
}
}
/**
* 类是核心
* 1. 包含最新的天气情况信息
* 2. 含有 CurrentConditions 对象
* 3. 当数据有更新时,就主动的调用 CurrentConditions 对象 update 方法(含 display), 这样他们(接入方)就看到最新的信息
*/
class WeatherData {
private float temperatrue;
private float pressure;
private float humidity;
/**
* 加入新的第三方
*/
private CurrentConditions currentConditions;
public WeatherData(CurrentConditions currentConditions) {
this.currentConditions = currentConditions;
}
/**
* 当数据有更新时,就调用 setData
*/
public void setData(float temperature, float pressure, float humidity) {
this.temperatrue = temperature;
this.pressure = pressure;
this.humidity = humidity;
//调用 dataChange, 将最新的信息 推送给 接入方 currentConditions
dataChange();
}
private void dataChange() {
//调用接入方的 update
currentConditions.update(getTemperature(), getPressure(), getHumidity());
}
private float getTemperature() {
return temperatrue;
}
private float getPressure() {
return pressure;
}
private float getHumidity() {
return humidity;
}
}
public void dataChange() {
currentConditions.update(getTemperature(), getPressure(), getHumidity());
}
* registerObserver 注册
* removeObserver 移除
* notifyObservers() 通知所有的注册的用户,根据不同需求,可以是更新数据,让用户来取,也可能是实施推送,看具体需求定
public class ObserverCase {
public static void main(String[] args) {
// 创建一个 WeatherData
WeatherData weatherData = new WeatherData();
// 创建观察者
CurrentCondition currentConditions = new CurrentCondition();
BaiduSite baiduSite = new BaiduSite();
// 注册到 weatherData
weatherData.registerObserver(currentConditions);
weatherData.registerObserver(baiduSite);
// 测试
System.out.println("通知各个注册的观察者, 看看信息");
weatherData.setData(10f, 100f, 30.3f);
// 测试移除
weatherData.removeObserver(currentConditions);
System.out.println(); System.out.println("通知各个注册的观察者, 看看信息");
weatherData.setData(10f, 100f, 30.3f);
}
}
/**
* 目标接口
*/
interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}
/**
* 观察者接口
*/
interface Observer {
void update(float temperature, float pressure, float humidity);
}
/**
* 具体目标-核心:天气信息
* 1. 包含最新的天气情况信息
* 2. 含有 观察者集合,使用 ArrayList 管理
* 3. 当数据有更新时,就主动的调用 ArrayList, 通知所有的(接入方)就看到最新的信息
*/
class WeatherData implements Subject {
private float temperatrue;
private float pressure;
private float humidity;
/**
* 观察者集合
*/
private List<Observer> observers = new ArrayList<>();
public void setData(float temperature, float pressure, float humidity) {
this.temperatrue = temperature;
this.pressure = pressure;
this.humidity = humidity;
//调用 dataChange, 将最新的信息 推送给 接入方 currentConditions
dataChange();
}
private void dataChange() {
notifyObservers();
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(temperatrue, pressure, humidity);
}
}
}
/**
* 具体观察者
*/
class CurrentCondition implements Observer {
/**
* 温度、气压、湿度
*/
private float temperature;
private float pressure;
private float humidity;
/**
* 更新 天气情况,是由 WeatherData 来调用 ==>> 使用推送模式
*/
@Override
public void update(float temperature, float pressure, float humidity) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
display();
}
/**
* 显示
*/
private void display() {
System.out.println("====气象局====");
System.out.println("***Today temperature: " + temperature + "***");
System.out.println("***Today pressure: " + pressure + "***");
System.out.println("***Today humidity: " + humidity + "***");
}
}
class BaiduSite implements Observer {
private float temperature;
private float pressure;
private float humidity;
@Override
public void update(float temperature, float pressure, float humidity) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
display();
}
private void display() {
System.out.println("====百度网站====");
System.out.println("***百度网站 气温 : " + temperature + "***");
System.out.println("***百度网站 气压: " + pressure + "***");
System.out.println("***百度网站 湿度: " + humidity + "***");
}
}
public class Observable {
private boolean changed = false;
private Vector<Observer> obs;
public Observable() {
obs = new Vector<>();
}
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}
public void notifyObservers() {
notifyObservers(null);
}
public void notifyObservers(Object arg) {
Object[] arrLocal;
synchronized (this) {
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
public synchronized void deleteObservers() {
obs.removeAllElements();
}
protected synchronized void setChanged() {
changed = true;
}
protected synchronized void clearChanged() {
changed = false;
}
public synchronized boolean hasChanged() {
return changed;
}
public synchronized int countObservers() {
return obs.size();
}
}
↓↓↓↓↓
public interface Observer {
void update(Observable o, Object arg);
}
public class MediatorCase {
public static void main(String[] args) {
// 创建一个中介者对象
Mediator mediator = new ConcreteMediator();
// 创建一个 Alarm 并加入到 ConcreteMediator 的Map中
Alarm alarm = new Alarm(mediator, "alarm");
// 创建一个 CoffeeMachine 并加入到 ConcreteMediator 的Map中
CoffeeMachine coffeeMachine = new CoffeeMachine(mediator, "coffeeMachine");
// 创建一个 Curtains 并加入到 ConcreteMediator 的Map中
Curtains curtains = new Curtains(mediator, "curtains");
TV tv = new TV(mediator, "tv");
// 让闹钟发出消息
alarm.sendMessage(0);
coffeeMachine.finishCoffee();
alarm.sendMessage(1);
}
}
/**
* 中介者:抽象类
*/
abstract class Mediator {
/**
* 将一个同事类加入到集合
*/
abstract void register(String colleagueName, Colleague colleague);
/**
* 接收消息,具体的同事对象发出
*/
abstract void getMessage(int stateChange, String colleagueName);
abstract void sendMessage();
}
/**
* 具体的中介者类
*/
class ConcreteMediator extends Mediator {
/**
* 集合:放入了所有的同事类
*/
private Map<String, Colleague> colleagueMap;
private Map<String, String> interMap;
ConcreteMediator() {
colleagueMap = new HashMap<>();
interMap = new HashMap<>();
}
@Override
void register(String colleagueName, Colleague colleague) {
colleagueMap.put(colleagueName, colleague);
if (colleague instanceof Alarm) {
interMap.put("Alarm", colleagueName);
} else if (colleague instanceof CoffeeMachine) {
interMap.put("CoffeeMachine", colleagueName);
} else if (colleague instanceof TV) {
interMap.put("TV", colleagueName);
} else if (colleague instanceof Curtains) {
interMap.put("Curtains", colleagueName);
}
}
@Override
void getMessage(int stateChange, String colleagueName) {
Colleague colleague = colleagueMap.get(colleagueName);
if (colleague instanceof Alarm) {
if (stateChange == 0) {
((CoffeeMachine) colleagueMap.get(interMap.get("CoffeeMachine"))).startCoffee();
((TV) colleagueMap.get(interMap.get("TV"))).startTV();
} else if (stateChange == 1) {
((TV) colleagueMap.get(interMap.get("TV"))).stopTV();
}
} else if (colleague instanceof CoffeeMachine) {
((Curtains) colleagueMap.get(interMap.get("Curtains"))).upCurtains();
} else if (colleague instanceof TV) {
// ...
} else if (colleague instanceof Curtains) {
// ...
}
}
@Override
void sendMessage() {
}
}
/**
* 同事:抽象类
*/
abstract class Colleague {
private Mediator mediator;
protected String name;
Colleague(Mediator mediator, String name) {
this.mediator = mediator;
this.name = name;
}
public Mediator getMediator() {
return mediator;
}
abstract void sendMessage(int stateChange);
}
/**
* 具体的同事类
*/
class Alarm extends Colleague {
Alarm(Mediator mediator, String name) {
super(mediator, name);
// 在创建Alarm对象时,将自己放入到ConcreteMediator对象中
mediator.register(name, this);
}
@Override
void sendMessage(int stateChange) {
// 调用中介者对象的 getMessage
this.getMediator().getMessage(stateChange, this.name);
}
public void sendAlarm(int stateChange) {
this.sendMessage(stateChange);
}
}
class CoffeeMachine extends Colleague {
CoffeeMachine(Mediator mediator, String name) {
super(mediator, name);
mediator.register(name, this);
}
@Override
void sendMessage(int stateChange) {
this.getMediator().getMessage(stateChange, this.name);
}
public void startCoffee() {
System.out.println("It's time to start coffee!");
}
public void finishCoffee() {
System.out.println("After 5 minutes!");
System.out.println("Coffee is OK!");
sendMessage(0);
}
}
class TV extends Colleague {
TV(Mediator mediator, String name) {
super(mediator, name);
mediator.register(name, this);
}
@Override
void sendMessage(int stateChange) {
this.getMediator().getMessage(stateChange, this.name);
}
public void startTV() {
System.out.println("It's time to Start TV!");
}
public void stopTV() {
System.out.println("Stop TV!");
}
}
class Curtains extends Colleague {
Curtains(Mediator mediator, String name) {
super(mediator, name);
mediator.register(name, this);
}
@Override
void sendMessage(int stateChange) {
this.getMediator().getMessage(stateChange, this.name);
}
public void upCurtains() {
System.out.println("I am holding Up Curtains!");
}
}
//It's time to start coffee!
//It's time to Start TV!
//After 5 minutes!
//Coffee is OK!
//I am holding Up Curtains!
//Stop TV!
public class MementoCase {
public static void main(String[] args) {
Originator originator = new Originator();
Caretaker caretaker = new Caretaker();
originator.setState("状态1 攻击力100");
// 保存当前状态
caretaker.add(originator.saveStateMemento());
System.out.println("当前的状态是:" + originator.getState());
originator.setState("状态2 攻击力80");
caretaker.add(originator.saveStateMemento());
System.out.println("当前的状态是:" + originator.getState());
originator.setState("状态3 攻击力30");
caretaker.add(originator.saveStateMemento());
System.out.println("当前的状态是:" + originator.getState());
// 状态恢复
originator.recoveryState(caretaker.get(1));
System.out.println("恢复到状态2:" + originator.getState());
}
}
@Data
class Originator {
private String state;
/**
* 编写一个方法,可以保存一个状态对象Memento
*/
public Memento saveStateMemento() {
return new Memento(state);
}
/**
* 通过备忘录对象,恢复状态
*/
public void recoveryState(Memento memento) {
state = memento.getState();
}
}
class Memento {
private String state;
Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
class Caretaker {
/**
* 在List集合中有很多备忘录对象
*/
private List<Memento> mementos = new ArrayList<>();
public void add(Memento memento) {
mementos.add(memento);
}
public Memento get(int index) {
return mementos.get(index);
}
}
通过解释器模式来实现四则运算,如计算a+b-c的值,具体要求:
public class InterpreterCase {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String expStr = getExpStr(scanner);
Map<String, Integer> var = getValue(expStr, scanner);
Calculator calculator = new Calculator(expStr);
System.out.println(expStr + "的运算结果:" + calculator.run(var));
}
private static String getExpStr(Scanner scanner) {
System.out.println("请输入表达式:");
return scanner.nextLine();
}
private static Map<String, Integer> getValue(String expStr, Scanner scanner) {
Map<String, Integer> map = new HashMap<>(8);
for (char ch : expStr.toCharArray()) {
if (ch != '+' && ch != '-') {
String key = String.valueOf(ch);
if (!map.containsKey(key)) {
System.out.println("请输入" + key +"的值");
int value = scanner.nextInt();
map.put(key, value);
}
}
}
return map;
}
}
/**
* 抽象类表达式,通过Map键值对,可以获取到变量的值
*/
abstract class AbsExpression {
/**
* a + b + c
* 解释公式和值,key就是公式(表达式)参数[a, b, c],value就是具体值
* 比如: {a: 10, b: 20}
*/
abstract int interpret(Map<String, Integer> var);
}
/**
* 变量的解释器
*/
class VarExpression extends AbsExpression {
/**
* 变量的key,key=a,b,c,...
*/
private String key;
VarExpression(String key) {
this.key = key;
}
@Override
int interpret(Map<String, Integer> var) {
return var.get(this.key);
}
}
/**
* 抽象运算符号解释器,这里每个运算符号都只和自己左右两个数字有关系
* 但左右两个数字有可能也是一个解析的结果,无论何种类型,都是Expression的实现类
*/
class SymbolExpression extends AbsExpression {
protected AbsExpression left;
protected AbsExpression right;
SymbolExpression(AbsExpression left, AbsExpression right) {
this.left = left;
this.right = right;
}
/**
* 这里是一个空实现,有具体的子类实现
*/
@Override
int interpret(Map<String, Integer> var) {
return 0;
}
}
/**
* 加法表达式
*/
class AddExpression extends SymbolExpression {
AddExpression(AbsExpression left, AbsExpression right) {
super(left, right);
}
@Override
public int interpret(Map<String, Integer> var) {
return left.interpret(var) + right.interpret(var);
}
}
/**
* 减法表达式
*/
class SubExpression extends SymbolExpression {
SubExpression(AbsExpression left, AbsExpression right) {
super(left, right);
}
@Override
public int interpret(Map<String, Integer> var) {
return left.interpret(var) - right.interpret(var);
}
}
/**
* 计算器
*/
class Calculator {
private AbsExpression expression;
Calculator(String expStr) {
Stack<AbsExpression> stack = new Stack<>();
AbsExpression left, right;
for (int i = 0; i < expStr.length(); i++) {
switch (expStr.charAt(i)) {
case '+':
left = stack.pop();
right = new VarExpression(String.valueOf(expStr.charAt(++i)));
stack.push(new AddExpression(left, right));
break;
case '-':
left = stack.pop();
right = new VarExpression(String.valueOf(expStr.charAt(++i)));
stack.push(new SubExpression(left, right));
break;
default:
stack.push(new VarExpression(String.valueOf(expStr.charAt(i))));
break;
}
}
this.expression = stack.pop();
}
public int run(Map<String, Integer> var) {
return this.expression.interpret(var);
}
}
public class InterpreterSpring {
public static void main(String[] args) {
//创建一个 Parser 对象
SpelExpressionParser parser = new SpelExpressionParser();
//通过 Parser 对象 获取到一个Expression对象
//会根据不同的 Parser 对象 ,返回不同的 Expression对象
Expression expression = parser.parseExpression("10 * (2 + 1) * 1 + 66");
int result = (Integer) expression.getValue();
System.out.println(result);
}
}
↓↓↓↓↓
public class SpelExpressionParser extends TemplateAwareExpressionParser {
private final SpelParserConfiguration configuration;
public SpelExpressionParser() {
this.configuration = new SpelParserConfiguration();
}
public SpelExpressionParser(SpelParserConfiguration configuration) {
Assert.notNull(configuration, "SpelParserConfiguration must not be null");
this.configuration = configuration;
}
public SpelExpression parseRaw(String expressionString) throws ParseException {
return doParseExpression(expressionString, null);
}
@Override
protected SpelExpression doParseExpression(String expressionString, @Nullable ParserContext context) throws ParseException {
return new InternalSpelExpressionParser(this.configuration).doParseExpression(expressionString, context);
}
}
请编写程序完成APP抽奖活动具体要求如下:
public class StateCase {
public static void main(String[] args) {
// 创建活动对象,奖品池有2个奖品
RaffleActivity activity = new RaffleActivity(2);
for (int i = 0; i < 100; i++) {
System.out.println("-----第" + (i + 1) + "次抽奖-----");
// 参加抽奖,第一步点击扣除积分
activity.deductMoney();
// 第二步抽奖
activity.raffle();
}
}
}
/**
* 抽象状态类
*/
abstract class State {
/**
* 扣除积分
*/
abstract void deductMoney();
/**
* 是否抽中奖品
*/
abstract boolean raffle();
/**
* 发放奖品
*/
abstract void dispensePrize();
}
@Data
class RaffleActivity {
/**
* 表示活动当前的状态,是变化的
*/
private State state;
/**
* 奖品数量
*/
private int count;
/**
* 四个属性,表示四种状态
*/
private State noRaffleState = new NoRaffleState(this);
private State canRaffleState = new CanRaffleState(this);
private State dispenseState = new DispenseState(this);
private State dispenseOutState = new DispenseOutState(this);
/**
* 初始化当前的状态为 noRafflleState(即不能抽奖的状态)
* 初始化奖品的数量
*/
public RaffleActivity(int count) {
this.state = getNoRaffleState();
this.count = count;
}
/**
* 扣分,调用当前状态为deductMoney
*/
public void deductMoney() {
state.deductMoney();
}
/**
* 抽奖
*/
public void raffle() {
// 如果当前的状态是抽奖成功
if (state.raffle()) {
// 领取奖品
state.dispensePrize();
}
}
/**
* 这里注意,每领取一次奖品,count--
*/
public int getCount() {
return count--;
}
}
/**
* 不能抽奖的状态
*/
class NoRaffleState extends State {
private RaffleActivity activity;
NoRaffleState(RaffleActivity activity) {
this.activity = activity;
}
/**
* 当前状态可以扣积分,扣除积分后,将状态设置为可以抽奖状态
*/
@Override
void deductMoney() {
System.out.println("扣除50积分成功,您可以抽奖了");
activity.setState(activity.getCanRaffleState());
}
/**
* 当前在不能抽奖状态
*/
@Override
boolean raffle() {
System.out.println("扣了积分才能抽奖哦!");
return false;
}
@Override
void dispensePrize() {
System.out.println("不能发放奖品");
}
}
/**
* 可以抽奖的状态
*/
class CanRaffleState extends State {
private RaffleActivity activity;
CanRaffleState(RaffleActivity activity) {
this.activity = activity;
}
/**
* 已经扣除了积分,不能再扣
*/
@Override
void deductMoney() {
System.out.println("已经扣除过积分了");
}
/**
* 可以抽奖, 抽完奖后,根据实际情况,改成新的状态
*/
@Override
boolean raffle() {
System.out.println("正在抽奖,请稍等");
int num = new Random().nextInt(10);
// 10%中奖机会
if (num == 0) {
// 改变活动状态为发放奖品
activity.setState(activity.getDispenseState());
return true;
} else {
System.out.println("很遗憾没有抽中奖品");
activity.setState(activity.getNoRaffleState());
return false;
}
}
/**
* 不能发放奖品
*/
@Override
void dispensePrize() {
System.out.println("没中奖,不能发放奖品");
}
}
/**
* 发放奖品的状态
*/
class DispenseState extends State {
private RaffleActivity activity;
DispenseState(RaffleActivity activity) {
this.activity = activity;
}
@Override
void deductMoney() {
System.out.println("不能扣除积分");
}
@Override
boolean raffle() {
System.out.println("不能抽奖");
return false;
}
/**
* 发放奖品
*/
@Override
void dispensePrize() {
if (activity.getCount() > 0) {
System.out.println("恭喜中奖了");
// 改变状态为不能抽奖
activity.setState(activity.getNoRaffleState());
} else {
System.out.println("很遗憾,奖品发放完了");
// 改变状态为奖品发送完毕,后面就不能发放奖品了
activity.setState(activity.getDispenseState());
}
}
}
/**
* 奖品发放完毕的状态
* 当我们 activity 改变成 DispenseOutState, 抽奖活动结束
*/
class DispenseOutState extends State {
private RaffleActivity activity;
DispenseOutState(RaffleActivity activity) {
this.activity = activity;
}
@Override
void deductMoney() {
System.out.println("奖品发放完了,请下次再参加");
}
@Override
boolean raffle() {
System.out.println("奖品发放完了,请下次再参加");
return false;
}
@Override
void dispensePrize() {
System.out.println("奖品发放完了,请下次再参加");
}
}
// TODO
abstract class Duck {
abstract void display();
void quack() {
System.out.println("鸭子嘎嘎叫");
}
void swim() {
System.out.println("鸭子会游泳");
}
void fly() {
System.out.println("鸭子会飞翔");
}
}
class WildDuck extends Duck {
@Override
void display() {
System.out.println("-- 野鸭 --");
}
}
class PekingDuck extends Duck {
@Override
void display() {
System.out.println("-- 北京鸭 --");
}
@Override
void fly() {
System.out.println("北京鸭不能飞翔");
}
}
class ToyDuck extends Duck {
@Override
void display() {
System.out.println("-- 玩具鸭 --");
}
@Override
void quack() {
System.out.println("玩具鸭不会叫");
}
@Override
void swim() {
System.out.println("玩具鸭不会游泳");
}
@Override
void fly() {
System.out.println("玩具鸭不会飞");
}
}
/**
* 飞翔行为:抽象策略类
*/
interface FlyBehavior {
void fly();
}
/**
* 下面是具体飞翔:具体策略类
*/
class GoodFlyBehavior implements FlyBehavior{
@Override
public void fly() {
System.out.println("飞翔技术高超");
}
}
class BadFlyBehavior implements FlyBehavior {
@Override
public void fly() {
System.out.println("飞翔水平一般");
}
}
class NoFlyBehavior implements FlyBehavior {
@Override
public void fly() {
System.out.println("不会飞翔");
}
}
/**
* 叫声行为:抽象策略类
*/
interface QuackBehavor {
void quack();
}
/**
* 下面是具体叫声:具体策略类
*/
class GaGaQuackBehavor implements QuackBehavor {
@Override
public void quack() {
System.out.println("嘎嘎叫");
}
}
class GeGeQuackBehavor implements QuackBehavor {
@Override
public void quack() {
System.out.println("咯咯叫");
}
}
class NoQuackBehavor implements QuackBehavor {
@Override
public void quack() {
System.out.println("不会叫");
}
}
/**
* 鸭子:环境类
*/
abstract class Duck {
FlyBehavior flyBehavior;
QuackBehavor quackBehavor;
abstract void display();
void quack() {
}
void fly() {
if (flyBehavior != null) {
flyBehavior.fly();
}
}
}
class WildDuck extends Duck {
WildDuck() {
flyBehavior = new GoodFlyBehavior();
quackBehavor = new GeGeQuackBehavor();
}
@Override
void display() {
System.out.println("-- 野鸭 --");
}
}
class PekingDuck extends Duck {
PekingDuck() {
flyBehavior = new BadFlyBehavior();
quackBehavor = new GaGaQuackBehavor();
}
@Override
void display() {
System.out.println("-- 北京鸭子 --");
}
}
class ToyDuck extends Duck {
ToyDuck() {
flyBehavior = new NoFlyBehavior();
quackBehavor = new NoQuackBehavor();
}
@Override
void display() {
System.out.println("-- 玩具鸭子 --");
}
}
public class JDKStrategy {
public static void main(String[] args) {
Integer[] data = {9, 1, 2, 8, 4, 3};
// 实现了 Comparator 接口(策略接口) , 匿名类 对象 new Comparator(){..}
// 对象 new Comparator(){..} 就是实现了 策略接口 的对象
// public int compare(Integer o1, Integer o2){} 指定具体的处理方式
Comparator<Integer> comparator = (o1, o2) -> (o1 > o2) ? 1 : -1;
Arrays.sort(data, comparator);
System.out.println(Arrays.toString(data));
}
}
↓↓↓↓↓
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
//...省略
}
↓↓↓↓↓
public static <T> void sort(T[] a, Comparator<? super T> c) {
if (c == null) {
// 就按照自己的方法排序
sort(a);
} else {
if (LegacyMergeSort.userRequested)
// 按照这个方式调用c
legacyMergeSort(a, c);
else
// 按照这个方式调用c比较器
TimSort.sort(a, 0, a.length, c, null, 0, 0);
}
}
采购员采购教学器材:
* 如果各个级别的人员审批金额发生变化,在客户端的也需要变化
* 客户端必须明确的知道有多少个审批级别和访问
public class ChainOfResponsibilityCase {
public static void main(String[] args) {
// 创建一个请求
PurchaseRequest request = new PurchaseRequest(1, 31000, 1);
// 创建各个级别的审批人
DepartmentApprover departmentApprover = new DepartmentApprover();
CollegeApprover collegeApprover = new CollegeApprover();
ViceShcoolMasterApprover viceShcoolMasterApprover = new ViceShcoolMasterApprover();
ShcoolMasterApprover shcoolMasterApprover = new ShcoolMasterApprover();
// 将各个审批级别的下一个审批人设置好,形成环
departmentApprover.setApprover(collegeApprover);
collegeApprover.setApprover(viceShcoolMasterApprover);
viceShcoolMasterApprover.setApprover(shcoolMasterApprover);
shcoolMasterApprover.setApprover(departmentApprover);
System.out.println("----开始从教学主任处理----");
departmentApprover.processRequest(request);
System.out.println("----开始从副校长处理----");
viceShcoolMasterApprover.processRequest(request);
}
}
/**
* 请求类
*/
@Data
@AllArgsConstructor
class PurchaseRequest {
private int type;
private float price;
private int id;
}
/**
* 审批人
*/
abstract class Approver {
/**
* 下一个处理者
*/
Approver approver;
String name;
Approver(String name) {
this.name = name;
}
public void setApprover(Approver approver) {
this.approver = approver;
}
abstract void processRequest(PurchaseRequest request);
}
/**
* 下面是具体的审批人
*/
class DepartmentApprover extends Approver {
DepartmentApprover() {
super("教学主任");
}
@Override
void processRequest(PurchaseRequest request) {
if (request.getPrice() <= 5000) {
System.out.println("采购单 id = " + request.getId() + " 被 " + this.name + " 审批");
} else {
System.out.println(this.name + " 审批不了");
approver.processRequest(request);
}
}
}
class CollegeApprover extends Approver {
CollegeApprover() {
super("院长");
}
@Override
void processRequest(PurchaseRequest request) {
if (request.getPrice() > 5000 && request.getPrice() <= 10000) {
System.out.println("采购单 id = " + request.getId() + " 被 " + this.name + " 审批");
} else {
System.out.println(this.name + " 审批不了");
approver.processRequest(request);
}
}
}
class ViceShcoolMasterApprover extends Approver {
ViceShcoolMasterApprover() {
super("副校长");
}
@Override
void processRequest(PurchaseRequest request) {
if (request.getPrice() > 10000 && request.getPrice() <= 30000) {
System.out.println("采购单 id = " + request.getId() + " 被 " + this.name + " 审批");
} else {
System.out.println(this.name + " 审批不了");
approver.processRequest(request);
}
}
}
class ShcoolMasterApprover extends Approver {
ShcoolMasterApprover() {
super("校长");
}
@Override
void processRequest(PurchaseRequest request) {
if (request.getPrice() > 30000) {
System.out.println("采购单 id = " + request.getId() + " 被 " + this.name + " 审批");
} else {
System.out.println(this.name + " 审批不了");
approver.processRequest(request);
}
}
}
//----开始从教学主任处理----
//教学主任 审批不了
//院长 审批不了
//副校长 审批不了
//采购单 id = 1 被 校长 审批
//----开始从副校长处理----
//副校长 审批不了
//采购单 id = 1 被 校长 审批
SpringMVC-HandlerExecutionChain 类就使用到职责链模式