个人解释一下上面的七大原则
一、创建型
创建型设计模式抽象了实例化过程,它们帮助一个系统独立于如何创建、组合和表示它的那些对象
二、结构型
结构型模式涉及如何组合类和对象以获得更大的结构,结构型模式采用继承机制来组合接口或实现
三、行为型
行为型模式涉及算法和对象间职责的分配。行为型模式不仅描述对象或类的模式,还描述它们之间的通信模式。这些模式刻画了在运行时难以跟踪的复杂的控制流。它们将你的注意力从控制流转移到对象间的联系方式上来
new
一下,但是这样你肯定要写参数,但是如果用简单工厂,我就写一个工厂类来处理这些操作,而不需要你去new
package org.example.factory;
/**
* @Author: ComingLiu
* @Date: 2022/10/30 20:53
*/
public interface Car {
void name();
}
package org.example.factory;
/**
* @Author: ComingLiu
* @Date: 2022/10/30 20:55
*/
public class Wuling implements Car{
@Override
public void name(){
System.out.println("五菱!");
}
}
package org.example.factory;
/**
* @Author: ComingLiu
* @Date: 2022/10/30 20:56
*/
public class TeSila implements Car{
@Override
public void name(){
System.out.println("特斯拉!");
}
}
package org.example.factory;
/**
* @Author: ComingLiu
* @Date: 2022/10/30 20:54
*/
public class Consumer {
public static void main(String[] args) {
Car car = new Wuling();
}
}
package org.example.factory;
/**
* @Author: ComingLiu
* @Date: 2022/10/30 20:54
*/
public class Consumer {
public static void main(String[] args) {
Car car = CarFactory.getCar("五菱");
}
}
new
,这样我们不用填写一些简单参数,就会比较方便ArrayList
中,package org.example.builder;
import java.util.ArrayList;
public abstract class Car {
// 方法执行顺序
private ArrayList<String> order = new ArrayList<>();
protected abstract void start();
protected abstract void stop();
protected abstract void alarm();
final public void run(){
for(String action : order){
switch (action){
case "start":{
this.start();
break;
}
case "stop":{
this.stop();
break;
}
case "alarm":{
this.alarm();
break;
}
default:{
break;
}
}
}
}
public Car setOrder(ArrayList<String> order) {
this.order = order;
return this;
}
}
package org.example.builder;
public class TeSila extends Car{
@Override
protected void start() {
System.out.println("TeSila started.");
}
@Override
protected void stop() {
System.out.println("TeSila stopped.");
}
@Override
protected void alarm() {
System.out.println("TeSila alarmed.");
}
}
package org.example.builder;
public class WuLing extends Car{
@Override
protected void start() {
System.out.println("WuLing started.");
}
@Override
protected void stop() {
System.out.println("WuLing stopped.");
}
@Override
protected void alarm() {
System.out.println("WuLing alarmed");
}
}
package org.example.builder;
import java.util.ArrayList;
public class Client {
public static void main(String[] args) {
TeSila car = new TeSila();
ArrayList<String> order = new ArrayList<>();
order.add("start");
order.add("alarm");
order.add("stop");
car.setOrder(order);
car.run();
}
}
package org.example.builder;
import java.util.ArrayList;
public abstract class CarBuilder {// 汽车建造者
public abstract void setOrder(ArrayList<String> sequence);
public abstract Car getCar();
}
package org.example.builder;
import java.util.ArrayList;
public class TeSilaBuilder extends CarBuilder{// 特斯拉建造者
private final TeSila car = new TeSila();
@Override
public void setOrder(ArrayList<String> order) {
car.setOrder(order);
}
@Override
public TeSila getCar() {
return car;
}
}
package org.example.builder;
import java.util.ArrayList;
public class WuLingBuilder extends CarBuilder{// 五菱建造者
private final WuLing car = new WuLing();
@Override
public void setOrder(ArrayList<String> order) {
car.setOrder(order);
}
@Override
public WuLing getCar() {
return car;
}
}
package org.example.builder;
import java.util.ArrayList;
public class Client {
public static void main(String[] args) {
TeSilaBuilder teSilaBuilder = new TeSilaBuilder();
WuLingBuilder wuLingBuilder = new WuLingBuilder();
ArrayList<String> order = new ArrayList<>();
order.add("start");
order.add("alarm");
order.add("stop");
teSilaBuilder.setOrder(order);
TeSila car = teSilaBuilder.getCar();
car.run();
wuLingBuilder.setOrder(order);
WuLing car2 = wuLingBuilder.getCar();
car2.run();
}
}
package org.example.single;
/**
* @Author: ComingLiu
* @Date: 2022/11/4 0:19
*/
public class Hungry {
private byte[] data1 = new byte[1024 * 1024];
private byte[] data2 = new byte[1024 * 1024];
private byte[] data3 = new byte[1024 * 1024];
private byte[] data4 = new byte[1024 * 1024];
private Hungry(){
}
private final static Hungry HUNGRY = new Hungry();
public static Hungry getInstance(){
return HUNGRY;
}
}
package org.example.single;
/**
* @Author: ComingLiu
* @Date: 2022/11/4 0:21
*/
public class LazyMan {
private LazyMan(){
}
private volatile static LazyMan lazyMan;// 防止指令重排
public static LazyMan getInstance(){
if(lazyMan == null){
synchronized (LazyMan.class){
if(lazyMan == null){
lazyMan = new LazyMan();// 不是原子操作
/**
* 1. 分配内存空间
* 2. 执行构造方法, 初始化对象
* 3. 把这个对象指向这个空间
* (可能指令重排, 导致没有完成构造方法)
*/
}
}
}
return lazyMan;
}
}
new
一个对象要经历三步,首先是分配内存空间;然后执行构造方法,初始化对象;最后是把这个对象指向这个分配的空间。那么根据happens-before原则,后两步的指令是可以互换的,如果它们发生了互换,那么并发环境下可能出现一个线程尚未初始化对象然后另一个线程访问到了这个对象,当前这个对象尚未初始化但已经分配了内存空间,那么这个对象当然不是空,所以必须禁止这两步之间的指令重排package org.example.single;
public class staticSingleton {
private staticSingleton(){
}
private static class InstanceHolder{
private final static staticSingleton instance = new staticSingleton();
}
public static staticSingleton getInstance(){
return InstanceHolder.instance;
}
}
package org.example.single;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class singleTest {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class objectClass = Class.forName("org.example.single.LazyMan");
Constructor constructor = objectClass.getDeclaredConstructor();
constructor.setAccessible(true);
LazyMan lazyMan = (LazyMan) constructor.newInstance();
System.out.println(lazyMan);
System.out.println(LazyMan.getInstance());
}
}
package org.example.single;
public enum enumSingleton {
INSTANCE;
private enumSingleton() {
}
public static enumSingleton getInstance() {
return INSTANCE;
}
}
package org.example.prototype;
import java.util.Date;
/**
* @Author: ComingLiu
* @Date: 2022/11/4 0:41
*/
public class Video implements Cloneable{
private String name;
private Date createTime;
@Override
protected Object clone() throws CloneNotSupportedException{
return super.clone();
}
public Video(){
}
public Video(String name, Date createTime) {
this.name = name;
this.createTime = createTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "Video{" +
"name='" + name + '\'' +
", createTime=" + createTime +
'}';
}
}
package org.example.prototype;
import java.util.Date;
/**
* @Author: ComingLiu
* @Date: 2022/11/4 0:47
*/
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
Date date = new Date();
Video v1 = new Video("hello", date);
Video v2 = (Video) v1.clone();// 浅克隆, 基本类型拷贝, 引用类型指向同一地址
System.out.println(v1);
System.out.println(v2);
date.setTime(123);
System.out.println(v1);
System.out.println(v2);
}
}
package org.example.prototype;
import java.util.Date;
/**
* @Author: ComingLiu
* @Date: 2022/11/4 0:41
*/
public class Video implements Cloneable{
private String name;
private Date createTime;
@Override
protected Object clone() throws CloneNotSupportedException{
// 深克隆, 或者序列化反序列化
Video v = (Video) super.clone();
v.createTime = (Date) this.createTime.clone();// 将这个对象的属性也进行克隆
return v;
}
public Video(){
}
public Video(String name, Date createTime) {
this.name = name;
this.createTime = createTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "Video{" +
"name='" + name + '\'' +
", createTime=" + createTime +
'}';
}
}
clone()
方法首先写一个类,让它有一个两孔插座
package org.example.adapter;
public class Hotel {
private TwoHole twoHole = new TwoHoleImpl();
public void setThreeHole(TwoHole twoHole){
this.twoHole = twoHole;
}
public void charge(){
twoHole.charge();
}
}
package org.example.adapter;
public interface TwoHole {
void charge();
}
package org.example.adapter;
public class TwoHoleImpl implements TwoHole{
@Override
public void charge() {
System.out.println("使用两孔插头充电");
}
}
写好两孔插座接口和实现,现在调用显然是两孔插座的充电方法,但是我现在只有三孔插头,那我再写一个三孔插头的接口和实现
package org.example.adapter;
public interface ThreeHole {
void charge();
}
package org.example.adapter;
public class ThreeHoleImpl implements ThreeHole{
@Override
public void charge() {
System.out.println("使用三孔插头充电");
}
}
那么现在我要加上一个适配器,把三孔插头转换为两孔插头
package org.example.adapter;
public class TwoHoleAdapter implements TwoHole{
private ThreeHole threeHole = new ThreeHoleImpl();
public TwoHoleAdapter(ThreeHole threeHole){
this.threeHole = threeHole;
}
@Override
public void charge() {
threeHole.charge();
}
}
测试类如下
package org.example.adapter;
public class Adapter {
public static void main(String[] args) {
Hotel hotel = new Hotel();
hotel.charge();
ThreeHole threeHole = new ThreeHoleImpl();
TwoHoleAdapter twoHoleAdapter = new TwoHoleAdapter(threeHole);// 三孔变两孔
hotel.setThreeHole(twoHoleAdapter);// 用三孔充电
hotel.charge();
}
}
可以实现使用两孔的插头给三孔充电器充电
package org.example.bridge;
public interface DrawAPI {
void drawCircle();
}
package org.example.bridge;
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
package org.example.bridge;
public class Circle extends Shape{
private final int x, y, r;
protected Circle(int x, int y, int r, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.r = r;
}
@Override
public void draw() {
drawAPI.drawCircle(x, y, r);
}
}
package org.example.bridge;
public class RedCircle implements DrawAPI{
@Override
public void drawCircle(int x, int y, int r) {
System.out.printf("Red x=%d, y=%d, r=%d\n", x, y, r);
}
}
package org.example.bridge;
public class GreenCircle implements DrawAPI{
@Override
public void drawCircle(int x, int y, int r) {
System.out.printf("Green x=%d, y=%d, r=%d\n", x, y, r);
}
}
package org.example.bridge;
public class BridgeDemo {
public static void main(String[] args) {
Circle redCircle = new Circle(1, 2, 3, new RedCircle());
Circle greenCircle = new Circle(1, 2, 3, new GreenCircle());
redCircle.draw();
greenCircle.draw();
}
}
比如下面的例子,一个员工会有一些下属
package org.example.composite;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Employee {
private String name;
private String job;
private Integer salary;
List<Employee> subordinates;
public Employee(String name, String job, Integer salary){
this.name = name;
this.job = job;
this.salary = salary;
this.subordinates = new ArrayList<>();
}
public void add(Employee e){
subordinates.add(e);
}
public void remove(Employee e){
subordinates.remove(e);
}
public List<Employee> getSubordinates(){
return subordinates;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", job='" + job + '\'' +
", salary=" + salary +
", subordinates=" + subordinates +
'}';
}
}
下属还会有下属,这样递归下去的设计模式就是组合模式
package org.example.composite;
public class EmployeeDemo {
public static void main(String[] args) {
Employee CEO = new Employee("John","CEO", 30000);
Employee headSales = new Employee("Robert","Head Sales", 20000);
Employee headMarketing = new Employee("Michel","Head Marketing", 20000);
Employee clerk1 = new Employee("Laura","Marketing", 10000);
Employee clerk2 = new Employee("Bob","Marketing", 10000);
Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
Employee salesExecutive2 = new Employee("Rob","Sales", 10000);
CEO.add(headSales);
CEO.add(headMarketing);
headSales.add(salesExecutive1);
headSales.add(salesExecutive2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
System.out.println(CEO);
for(Employee e : CEO.getSubordinates()){
System.out.println(e);
for(Employee e2 : e.getSubordinates()){
System.out.println(e2);
}
}
}
}
package org.example.decorator;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/08/18:20
* @Description:
*/
public class RobotDecorator implements Robot{
private final Robot robot;
public RobotDecorator(Robot robot){
this.robot = robot;
}
@Override
public void doSomeThing() {
robot.doSomeThing();
}
public void doMoreThing(){
System.out.println("走路");
}
}
package org.example.decorator;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/08/18:19
* @Description:
*/
public class FirstRobot implements Robot{
@Override
public void doSomeThing() {
System.out.println("唱歌");
}
}
package org.example.decorator;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/08/17:57
* @Description:
*/
public interface Robot {
void doSomeThing();
}
package org.example.decorator;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/08/21:37
* @Description:
*/
public class Decorator {
public static void main(String[] args) {
RobotDecorator decorator = new RobotDecorator(new FirstRobot());
decorator.doMoreThing();
}
}
FileInputStream inputStream=new FileInputStream(file);
//把inputStream装饰成BufferedReader来成为具备缓冲能力的reader
BufferedReader reader=new BufferedReader(inputStreamReader);
package org.example.facade;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/10/0:32
* @Description:
*/
public class Facade {
System1 system1 = new System1();
System2 system2 = new System2();
System3 system3 = new System3();
boolean prove(){
return system1.module() && system2.module() && system3.module();
}
}
package org.example.facade;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/10/0:29
* @Description:
*/
public class System1 {
boolean module(){
return true;
}
}
package org.example.facade;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/10/0:31
* @Description:
*/
public class System2 {
boolean module(){
return true;
}
}
package org.example.facade;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/10/0:32
* @Description:
*/
public class System3 {
boolean module(){
return true;
}
}
package org.example.facade;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/10/0:29
* @Description:
*/
public class FacadePattern {
public static void main(String[] args) {
Facade facade = new Facade();
if(facade.prove()){
System.out.println("子模块正常");
}else{
System.out.println("子模块异常");
}
}
}
package org.example.flyweight;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/11/10:48
* @Description:
*/
abstract public class Bike {
protected Integer state = 0;
/**
* 使用
*/
abstract void ride(String username);
/**
* 归还
*/
abstract void back();
public Integer getState() {
return state;
}
}
package org.example.flyweight;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/11/10:49
* @Description:
*/
public class MoBike extends Bike{
private final String id;
public MoBike(String id){
this.id = id;
}
@Override
void ride(String username) {
state = 1;
System.out.println(username + "骑" + id + "出行");
}
@Override
void back() {
state = 0;
}
}
package org.example.flyweight;
import java.util.HashSet;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/11/10:52
* @Description:
*/
public class BikeFactory {
private static final BikeFactory instance = new BikeFactory();
private final Set<Bike> pool = new HashSet<>();
public static BikeFactory getInstance() {
return instance;
}
private BikeFactory(){// 饿汉式创建单例
for(int i=0;i<2;i++){
pool.add(new MoBike(i + "号"));
}
}
public Bike getBike(){
for(Bike bike : pool){
if(bike.getState() == 0){
return bike;
}
}
return null;
}
}
package org.example.flyweight;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/11/10:55
* @Description:
*/
public class FlyWeight {
public static void main(String[] args) {
Bike bike = BikeFactory.getInstance().getBike();
bike.ride("张三");
Bike bike1 = BikeFactory.getInstance().getBike();
bike1.ride("王五");
bike1.back();
Bike bike2 = BikeFactory.getInstance().getBike();
bike2.ride("李四");
}
}
package org.example.proxy;
public interface RentHouse {
void rentHouse();// 租房子
RentHouse getProxy();// 获取代理
}
package org.example.proxy;
public class IRentHouse implements RentHouse{
private IntermediaryProxy proxy = null;
@Override
public void rentHouse(){
if(hasProxy()){
System.out.println("调用真实角色的方法");
}else{
System.out.println("请使用代理调用");
}
}
@Override
public RentHouse getProxy() {
if(!hasProxy()){
this.proxy = new IntermediaryProxy(this);
}
return this;
}
private boolean hasProxy(){
return proxy != null;
}
}
package org.example.proxy;
public class IntermediaryProxy{
private RentHouse rentHouse = null;
public IntermediaryProxy(RentHouse iRentHouse){
this.rentHouse = iRentHouse;
}
public void rentHouse() {
rentHouse.rentHouse();
}
}
package org.example.proxy;
public class proxyTest {
public static void main(String[] args) {
RentHouse iRentHouse = new IRentHouse();
iRentHouse.getProxy().rentHouse();
}
}
package org.example.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class IntermediaryProxy implements InvocationHandler {
private final Object target;
public IntermediaryProxy(Object iRentHouse){
this.target = iRentHouse;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 功能增强
return method.invoke(target, args);
}
}
package org.example.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class proxyTest {
public static void main(String[] args) {
RentHouse iRentHouse = new IRentHouse();
// 定义一个handler
InvocationHandler handler = new IntermediaryProxy(iRentHouse);
// 获得类的class loader
ClassLoader cl = iRentHouse.getClass().getClassLoader();
// 动态产生一个消费者
RentHouse proxy = (RentHouse) Proxy.newProxyInstance(cl, new Class[]{RentHouse.class}, handler);
proxy.getProxy().rentHouse();
}
}
package org.example.chain;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/12/14:59
* @Description: 参与者类
*/
abstract class Handler {
protected Handler nextHandler;
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;// 链上的下一个节点
}
public abstract void process(Integer days);
}
package org.example.chain;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/12/15:04
* @Description:
*/
public class Leader extends Handler{
@Override
public void process(Integer days) {
if(days <= 1) {
System.out.println("Leader处理");
}
else {
nextHandler.process(days);
}
}
}
package org.example.chain;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/12/15:04
* @Description:
*/
public class Boss extends Handler{
@Override
public void process(Integer days) {
System.out.println("Boss处理");
}
}
package org.example.chain;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/12/14:59
* @Description:
*/
public class ChainOfResp {
public static void main(String[] args) {
Handler handler1 = new Leader();
Handler handler2 = new Boss();
handler1.setNextHandler(handler2);
handler1.process(1);
handler1.process(2);
}
}
package org.example.command;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/16/12:31
* @Description:
*/
public abstract class Command {
public abstract void execute();
public abstract void undo();
}
package org.example.command;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/16/12:32
* @Description:
*/
public class InsertCommand extends Command{
Content c;
String str = "456789";
public InsertCommand(Content c){
this.c = c;
}
@Override
public void execute() {
c.msg = c.msg + str;
}
@Override
public void undo() {
c.msg = c.msg.substring(0, c.msg.length() - str.length());
}
public Content getC() {
return c;
}
}
package org.example.command;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/16/12:33
* @Description:
*/
public class Content {
String msg;
public Content(String msg){
this.msg = msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
}
package org.example.command;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/16/12:53
* @Description:
*/
public class Main {
public static void main(String[] args) {
InsertCommand insertCommand = new InsertCommand(new Content("123"));
insertCommand.execute();
System.out.println(insertCommand.getC().getMsg());
insertCommand.undo();
System.out.println(insertCommand.getC().getMsg());
}
}
package org.example.intercepter;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/23/21:44
* @Description:
*/
public class Context {
String sequence;// 当前字符串
long value;// 当前值
public Context(String sequence){
this.sequence = sequence;
}
}
package org.example.intercepter;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/23/21:40
* @Description:
*/
public abstract class Expression {
abstract Long interpret(Context context) throws Exception;
Integer findNextNumber(Context context){// 找下一个数字
int ptr = 0;
int ans = 0;
while(ptr < context.sequence.length() && Character.isDigit(context.sequence.charAt(ptr))){
ans *= 10;
ans += context.sequence.charAt(ptr) - '0';
ptr += 1;
}
context.sequence = context.sequence.substring(ptr);
return ans;
}
Character findNextOpr(Context context) {// 找下一个操作符
int ptr = 0;
while(ptr < context.sequence.length() && Character.isDigit(context.sequence.charAt(ptr))){
ptr += 1;
}
if(ptr < context.sequence.length()) {
Character c = context.sequence.charAt(ptr);
context.sequence = context.sequence.substring(ptr + 1);
return c;
}else {
return null;
}
}
}
package org.example.intercepter;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/23/22:07
* @Description:
*/
public class AddExpression extends Expression{// 加号
private final static MinusExpression minusExpression = new MinusExpression();
private final static EqualsExpression equalsExpression = new EqualsExpression();
@Override
Long interpret(Context context) throws Exception {
int val = findNextNumber(context);
Character c = findNextOpr(context);
assert (c != null);
context.value = context.value + val;
switch (c){
case '+': {
return this.interpret(context);
}
case '-': {
return minusExpression.interpret(context);
}
case '=': {
return equalsExpression.interpret(context);
}
default: {
throw new Exception("error");
}
}
}
}
package org.example.intercepter;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/23/22:08
* @Description:
*/
public class MinusExpression extends Expression{// 减号
private final static AddExpression addExpression = new AddExpression();
private final static EqualsExpression equalsExpression = new EqualsExpression();
@Override
Long interpret(Context context) throws Exception {
int val = findNextNumber(context);
Character c = findNextOpr(context);
assert (c != null);
context.value = context.value - val;
switch (c){
case '+': {
return addExpression.interpret(context);
}
case '-': {
return this.interpret(context);
}
case '=': {
return equalsExpression.interpret(context);
}
default: {
throw new Exception("error");
}
}
}
}
package org.example.intercepter;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/23/22:09
* @Description:
*/
public class EqualsExpression extends Expression{// 等于号
@Override
Long interpret(Context context) {
return context.value;
}
}
package org.example.intercepter;
/**
* Created with IntelliJ IDEA.
*
* @Author: Clarence
* @Date: 2023/02/23/21:51
* @Description:
*/
public class InterpreterDemo {// 测试
public static void main(String[] args) throws Exception {
Context context = new Context("1+2-3+4-5+6=");
System.out.println(new AddExpression().interpret(context));
}
}
ArrayList
的迭代器来研究这种设计模式private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;// 类似金丝雀值, 每次对List做一次操作modCount会+1
// prevent creating a synthetic constructor
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
int i = cursor;
if (i < size) {
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
Fail-Fast
机制,如果金丝雀值被改变,迭代器会检测到这一异常,所以遍历元素的时候使用迭代器方法可能会更好send()
方法,让中介者转发到其他用户,代码实现如下首先定义抽象接口
package org.example.mediator;
public abstract class Mediator {
abstract void communication(Colleague colleague);
abstract void register(Colleague colleague);
}
package org.example.mediator;
public abstract class Colleague {
protected Mediator mediator;
public abstract void receive();
public abstract void send();
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
}
定义两个实体
package org.example.mediator;
public class Colleague1 extends Colleague{
@Override
public void receive() {
System.out.println("Colleague1 receives a message.");
}
@Override
public void send() {
System.out.println("Colleague1 sends a message.");
mediator.communication(this);
}
}
package org.example.mediator;
public class Colleague2 extends Colleague{
@Override
public void receive() {
System.out.println("Colleague2 receives a message.");
}
@Override
public void send() {
System.out.println("Colleague2 sends a message.");
this.mediator.communication(this);
}
}
定义一个中介者
package org.example.mediator;
import java.util.ArrayList;
public class ConcreteMediator extends Mediator{
private ArrayList<Colleague> colleagues;
ConcreteMediator() {
colleagues = new ArrayList<>();
}
@Override
void communication(Colleague colleague) {
colleagues.forEach(coll -> {
if(!coll.equals(colleague)) {
coll.receive();
}
});
}
@Override
void register(Colleague colleague) {
colleagues.add(colleague);
colleague.mediator = this;
}
}
然后调用,实现的功能就是通过中介者实现了消息的相互转发
package org.example.mediator;
public class MediatorDemo {
public static void main(String[] args) {
Colleague1 colleague1 = new Colleague1();
Colleague2 colleague2 = new Colleague2();
ConcreteMediator concreteMediator = new ConcreteMediator();
concreteMediator.register(colleague1);
concreteMediator.register(colleague2);
colleague1.send();
colleague2.send();
}
}
memento
是一个对象,它存储另一个对象在某个瞬间的内部状态,而后者成为备忘录的原发器originator
,当需要设置原发器的检查点时,取消操作机制会向原发器请求一个备忘录。原发器用描述当前状态的信息初始化该备忘录。只有原发器可以向备忘录中存取信息,备忘录对其他的对象不可见下面我们来使用备忘录模式实现一个类似版本维护的操作
package org.example.Memento;
import java.util.Date;
public class ConfigFile {
// 版本号
private String versionNo;
// 内容
private String content;
// 时间
private Date dateTime;
// 操作人
private String operator;
public ConfigFile(String versionNo, String content, Date dateTime, String operator) {
this.versionNo = versionNo;
this.content = content;
this.dateTime = dateTime;
this.operator = operator;
}
public void setContent(String content) {
this.content = content;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public void setOperator(String operator) {
this.operator = operator;
}
public void setVersionNo(String versionNo) {
this.versionNo = versionNo;
}
public String getContent() {
return content;
}
public Date getDateTime() {
return dateTime;
}
public String getOperator() {
return operator;
}
public String getVersionNo() {
return versionNo;
}
}
package org.example.Memento;
public class ConfigMemento {
private ConfigFile configFile;
public ConfigMemento(ConfigFile configFile) {
this.configFile = configFile;
}
public ConfigFile getConfigFile() {
return configFile;
}
public void setConfigFile(ConfigFile configFile) {
this.configFile = configFile;
}
}
originator
,感觉好像和备忘录没什么区别,个人理解备忘录是一个创建出来的东西,原发器是真正存在的,通过原发器操作备忘录package org.example.Memento;
public class ConfigOrinator {
private ConfigFile configFile;
public void setConfigFile(ConfigFile configFile) {
this.configFile = configFile;
}
public ConfigFile getConfigFile() {
return configFile;
}
public ConfigMemento saveMemento() {
return new ConfigMemento(this.configFile);
}
public void getMemento(ConfigMemento configMemento) {
this.configFile = configMemento.getConfigFile();
}
}
package org.example.Memento;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Caretaker {
private int cursorIndex = -1;// 当前所处的版本游标
private List<ConfigMemento> mementoList = new ArrayList<>();
private Map<String, ConfigMemento> mementoMap = new ConcurrentHashMap<>();
public void append(ConfigMemento configMemento) {
mementoList.add(configMemento);
mementoMap.put(configMemento.getConfigFile().getVersionNo(), configMemento);
cursorIndex += 1;
}
public ConfigMemento undo() {
if(--cursorIndex <= 0) {
return mementoList.get(0);
}
return mementoList.get(cursorIndex);
}
public ConfigMemento redo() {
if(++cursorIndex >= mementoList.size()) {
return mementoList.get(mementoList.size() - 1);
}
return mementoList.get(cursorIndex);
}
public ConfigMemento get(String versionNo) {
return mementoMap.get(versionNo);
}
public int getCursorIndex() {
return cursorIndex;
}
public void setCursorIndex(int cursorIndex) {
this.cursorIndex = cursorIndex;
}
}
package org.example.Memento;
import java.util.Date;
public class MementoDemo {
public static void main(String[] args) {
Caretaker taker = new Caretaker();
ConfigOrinator configOrinator = new ConfigOrinator();
configOrinator.setConfigFile(new ConfigFile("0", "配置0", new Date(), "clarence"));
taker.append(configOrinator.saveMemento());
configOrinator.setConfigFile(new ConfigFile("1", "配置1", new Date(), "clarence"));
taker.append(configOrinator.saveMemento());
configOrinator.setConfigFile(new ConfigFile("2", "配置2", new Date(), "clarence"));
taker.append(configOrinator.saveMemento());
configOrinator.setConfigFile(new ConfigFile("3", "配置3", new Date(), "clarence"));
taker.append(configOrinator.saveMemento());
System.out.println(configOrinator.getConfigFile().getVersionNo());
configOrinator.getMemento(taker.undo());
System.out.println(configOrinator.getConfigFile().getVersionNo());
configOrinator.getMemento(taker.undo());
System.out.println(configOrinator.getConfigFile().getVersionNo());
configOrinator.getMemento(taker.redo());
System.out.println(configOrinator.getConfigFile().getVersionNo());
configOrinator.getMemento(taker.get("0"));
System.out.println(configOrinator.getConfigFile().getVersionNo());
}
}
observer
,数据就是目标subject
,一个目标可以有任意数目的依赖于它的观察者,一旦目标的状态发生改变,所有的观察着都得到通知publish-subscribe
,我们在消息队列中也接触过这个概念接下来写个范例,目的是监听消息和简单模拟消息队列收消息
package org.example.observer;
import java.util.Date;
public class Event {
private String uid;
private String msg;
private Date time;
public Event(String uid, String msg, Date time) {
this.uid = uid;
this.msg = msg;
this.time = time;
}
public String getMsg() {
return msg;
}
public Date getTime() {
return time;
}
public String getUid() {
return uid;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setTime(Date time) {
this.time = time;
}
public void setUid(String uid) {
this.uid = uid;
}
}
package org.example.observer;
public interface EventListener {
void doEvent(Event event);
}
package org.example.observer;
public class MessageEventListener implements EventListener{
@Override
public void doEvent(Event event) {
System.out.println("MessageListener has received" + event.getUid() + "'s message" + event.getMsg());
}
}
package org.example.observer;
public class MqEventListener implements EventListener{
@Override
public void doEvent(Event event) {
System.out.println("MQ records user" + event.getUid() + "'s messages " + event.getMsg());
}
}
subject
,提供注册和删除观察者对象的接口package org.example.observer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EventManager {
Map<Enum<EventType>, List<EventListener>> listeners = new HashMap<>();
public enum EventType{
MQ, MESSAGE
}
@SafeVarargs
public EventManager(Enum<EventType>... operations) {
for(Enum<EventType> operation : operations) {
this.listeners.put(operation, new ArrayList<>());
}
}
/**
* 订阅
* @param eventType 事件类型
* @param listener 监听
*/
public void subscribe(Enum<EventType> eventType, EventListener listener) {
List<EventListener> users = listeners.get(eventType);
users.add(listener);
}
/**
* 取消订阅
* @param eventType 事件类型
* @param listener 监听
*/
public void unsubscribe(Enum<EventType> eventType, EventListener listener) {
List<EventListener> users = listeners.get(eventType);
users.remove(listener);
}
/**
* 通知
* @param eventType 事件类型
* @param event 事件
*/
public void notify(Enum<EventType> eventType, Event event) {
List<EventListener> users = listeners.get(eventType);
for(EventListener listener : users) {
listener.doEvent(event);
}
}
}
package org.example.observer;
public abstract class EventService {
private EventManager eventManager;
public EventService() {
eventManager = new EventManager(EventManager.EventType.MQ, EventManager.EventType.MESSAGE);
eventManager.subscribe(EventManager.EventType.MQ, new MqEventListener());
eventManager.subscribe(EventManager.EventType.MESSAGE, new MessageEventListener());
}
public Event draw(String uid) {
Event event = doDraw(uid);
eventManager.notify(EventManager.EventType.MQ, event);
eventManager.notify(EventManager.EventType.MESSAGE, event);
return event;
}
protected abstract Event doDraw(String uid);
}
package org.example.observer;
import java.util.Date;
public class EventServiceImpl extends EventService{
@Override
public Event doDraw(String uid) {
String msg = "user uid's messages";
System.out.println("System sends messages to user " + uid);
return new Event(uid, msg, new Date());
}
}
package org.example.observer;
import com.alibaba.fastjson2.JSON;
public class ObserverDemo {
public static void main(String[] args) {
EventService eventService = new EventServiceImpl();
Event result = eventService.draw("001");
System.out.println(JSON.toJSON(result));
}
}
if-else
或者switch-case
等语句,这样如果之后需要进行状态的修改,这个时候就违背了开闭原则,例如下面这个package org.example.state;
public class Person {
String name;
private enum State {HAPPY, SAD}
public void smile() {
// switch state
}
public void say() {
// switch state
}
public void cry() {
// switch state
}
}
case
,这是不好的package org.example.state;
public abstract class PersonState {
abstract void smile();
abstract void cry();
abstract void say();
}
package org.example.state;
public class HappyState extends PersonState{
@Override
void smile() {
// TODO Auto-generated method stub
}
@Override
void cry() {
// TODO Auto-generated method stub
}
@Override
void say() {
// TODO Auto-generated method stub
}
}
package org.example.state;
public class SadState extends PersonState{
@Override
void smile() {
// TODO Auto-generated method stub
}
@Override
void cry() {
// TODO Auto-generated method stub
}
@Override
void say() {
// TODO Auto-generated method stub
}
}
package org.example.state;
public class Person {
String name;
private PersonState state;
public Person(String name, PersonState state) {
this.name = name;
this.state = state;
}
public void smile() {
state.smile();
}
public void say() {
state.say();
}
public void cry() {
state.cry();
}
}
PersonState
抽象类加一个实现类即可,这就是状态模式if-else
嵌套超过三层,需要使用卫语句、策略模式、状态模式等来实现,卫语句就是在if
里面加一个return
,这样就不需要写else
了,策略模式是接下来要说的Dog
类package org.example.strategy;
public class Dog {
private int weight;
private int height;
public Dog(int weight, int height) {
this.weight = weight;
this.height = height;
}
@Override
public String toString() {
return "Dog{" + "weight=" + weight + ",height=" + height + "}";
}
public void setHeight(int height) {
this.height = height;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public int getWeight() {
return weight;
}
}
Height
排序,怎么做呢?策略模式的方法是写一个排序构造器接口package org.example.strategy;
public interface Comparator<T> {
int compare(T o1, T o2);
}
package org.example.strategy;
public class DogHeightComparator implements Comparator<Dog>{
@Override
public int compare(Dog o1, Dog o2) {
if(o1.getHeight() < o2.getHeight()) {
return -1;
}
if(o1.getHeight() > o2.getHeight()) {
return 1;
}
return 0;
}
}
package org.example.strategy;
public class Sorter<T> {
private Comparator<T> comparator;
private void quicksort(T[] t0, int l, int r) {
int i = l;
int j = r;
int mid = (r - l >>> 1) + l;
do {
while(comparator.compare(t0[i], t0[mid]) == -1) {
i += 1;
}
while(comparator.compare(t0[j], t0[mid]) == 1) {
j -= 1;
}
if(i <= j) {
swap(t0, i, j);
i += 1;
j -= 1;
}
}while(i <= j);
if(i < r) quicksort(t0, i, r);
if(j > l) quicksort(t0, l, j);
}
private void swap(T[] t0, int i, int j) {
T t1 = t0[i];
t0[i] = t0[j];
t0[j] = t1;
}
public void sort(T[] t0, Comparator<T> comparator) {
int n = t0.length;
this.comparator = comparator;
quicksort(t0, 0, n - 1);
}
}
package org.example.strategy;
public class StrategyDemo {
public static void main(String[] args) {
Dog[] dogs = new Dog[3];
for(int i=0;i<3;i++) {
dogs[i] = new Dog(i, 3 - i);
}
Sorter<Dog> sorter = new Sorter<Dog>();
sorter.sort(dogs, new DogHeightComparator());// 传入一个构造器
for(int i=0;i<3;i++) {
System.out.println(dogs[i]);
}
}
}
weight
排序,我只需要传入一个新的构造器即可;如果我希望对猫排序,我只需要改变泛型即可,这大大减小了代码的耦合度package org.example.templateMethod;
public abstract class F {
public void m() {
op1();
op2();
}
abstract void op1();
abstract void op2();
}
package org.example.templateMethod;
public class F1 extends F{
@Override
void op1() {
System.out.println("F1 - op1");
}
@Override
void op2() {
System.out.println("F1 - op2");
}
}
package org.example.templateMethod;
public class F2 extends F{
@Override
void op1() {
System.out.println("F2 - op1");
}
@Override
void op2() {
System.out.println("F2 - op2");
}
}
首先写一个抽象类
package org.example.visitor;
public abstract class ComputerPart {
abstract void accepted(Visitor v);
abstract double getPrice();
}
然后分别将三个部件功能实现
package org.example.visitor;
public class Board extends ComputerPart{
@Override
void accepted(Visitor v) {
v.visitBoard(this);
}
@Override
double getPrice() {
return 800;
}
}
package org.example.visitor;
public class Memory extends ComputerPart{
@Override
void accepted(Visitor v) {
v.visitMemory(this);
}
@Override
double getPrice() {
return 400;
}
}
package org.example.visitor;
public class CPU extends ComputerPart{
@Override
void accepted(Visitor v) {
v.visitCpu(this);
}
@Override
double getPrice() {
return 1000;
}
}
然后写一个访问者接口
package org.example.visitor;
public interface Visitor {
double totalPrice = 0.0;
void visitCpu(CPU cpu);
void visitBoard(Board board);
void visitMemory(Memory memory);
}
package org.example.visitor;
public class PersonVisitor implements Visitor{
private double totalPrice = 0.0;
@Override
public void visitCpu(CPU cpu) {
totalPrice += cpu.getPrice() * 0.9;
}
@Override
public void visitBoard(Board board) {
totalPrice += board.getPrice() * 0.9;
}
@Override
public void visitMemory(Memory memory) {
totalPrice += memory.getPrice() * 0.9;
}
public double getTotalPrice() {
return totalPrice;
}
}
package org.example.visitor;
public class CompanyVisitor implements Visitor {
private double totalPrice = 0.0;
@Override
public void visitCpu(CPU cpu) {
totalPrice += cpu.getPrice() * 0.8;
}
@Override
public void visitBoard(Board board) {
totalPrice += board.getPrice() * 0.8;
}
@Override
public void visitMemory(Memory memory) {
totalPrice += memory.getPrice() * 0.8;
}
public double getTotalPrice() {
return totalPrice;
}
}