23种设计模式

创建型设计模式

一、SimpleFactory(简单工厂模式)

/**
 *  简单工厂模式
 */

public class SimpleFactory {
    public static void main(String[] args){
       Product productA = Factory.createProduct("A");
       productA.into();

        Product productB = Factory.createProduct("B");
        productB.into();
    }
}

class Factory {

    public static Product createProduct(String type){
        Product product = null;

        switch (type){
            case "A":
                product = new ProductA();
            case "B":
                product = new ProductB();
            case "C":
                product = new ProductC();
            default:
                System.out.println("没有"+type+"类型");
        }
        return product;
    }
}

abstract class Product{
    public abstract void into();
}

class ProductA extends Product{
    @Override
    public void into() {
        System.out.println("产品的信息:A");
    }
}

class ProductB extends Product{
    @Override
    public void into() {
        System.out.println("产品的信息:B");
    }
}

class ProductC extends Product{
    @Override
    public void into() {
        System.out.println("产品的信息:C");
    }
}

二、FactoryMethod(工厂方法模式)

/**
 * 工厂模式
 */

public class FactoryMethod {
    public static void main(String[] args) {
        Factory factoryA = new FactoryA();

        Product productA = factoryA.createProduct();
        productA.into();

        Factory factoryB = new FactoryA();

        Product productB = factoryA.createProduct();
        productB.into();
    }
}

interface Factory {

    public Product createProduct();
}

class FactoryA implements Factory {
    @Override
    public Product createProduct() {
        return new ProductA();
    }
}

class FactoryB implements Factory {
    @Override
    public Product createProduct() {
        return new ProductB();
    }
}

interface Product {
    public void into();
}

class ProductA implements Product {
    @Override
    public void into() {
        System.out.println("产品的信息:A");
    }
}

class ProductB implements Product {
    @Override
    public void into() {
        System.out.println("产品的信息:B");
    }
}

class ProductC implements Product {
    @Override
    public void into() {
        System.out.println("产品的信息:C");
    }
}

三、AbstractFactory(抽象工厂模式)

/**
 * 抽象工厂模式
 */

public class AbstractFactory {
    public static void main(String[] args) {
        Factory factory1 = new Factory1();

        ProductA productA = factory1.createProductA();
        productA.into();

        Factory factory2 = new Factory2();

        ProductB productB = factory2.createProductB();
        productA.into();
    }
}

// class Factory
interface Factory {
    public ProductA createProductA();
    public ProductB createProductB();
}

class Factory1 implements Factory {
    @Override
    public ProductA createProductA() {
        return new ProductA1();
    }

    @Override
    public ProductB createProductB() {
        return new ProductB1();
    }
}

class Factory2 implements Factory {
    @Override
    public ProductA createProductA() {
        return new ProductA2();
    }

    @Override
    public ProductB createProductB() {
        return new ProductB2();
    }
}

// abstract class product
interface ProductA {
    // public abstract void info();
    public void into();
}

// class ProductA extends Product
class ProductA1 implements ProductA {
    @Override
    public void into() {
        System.out.println("产品的信息:A1");
    }
}

class ProductA2 implements ProductA {
    @Override
    public void into() {
        System.out.println("产品的信息:A2");
    }
}

interface ProductB{
    public void into();
}

class ProductB1 implements ProductB {
    @Override
    public void into() {
        System.out.println("产品的信息:B1");
    }
}

class ProductB2 implements ProductB {
    @Override
    public void into() {
        System.out.println("产品的信息:B2");
    }
}

四、Builder(生成器)

/**
 *生成器模式
 */

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args){
        Director director = new Director();

        Builder builder1 = new Builder1(); // 1、创建
        director.Construct(builder1);  // 2、把套餐加入到director中
        Product product1 = builder1.getResult(); // 3、product获取返回的套餐构建
        product1.show();  // 打印

        Builder builder2 = new Builder1(); // 生成一个套餐2
        director.Construct(builder2); // director根据生成器创建一个对应的产品
        Product product2 = builder2.getResult(); // 获取对应的产品并接收
        product2.show(); // 查看零件组成
    }
}

abstract class  Builder {
    public abstract void BuildPart();
    public abstract Product getResult();
}

class Director {
    public  void Construct(Builder builder){
        builder.BuildPart();
    }
}

class Builder1 extends Builder{
    Product product = new Product();

    @Override
    public void BuildPart() {
        product.add("A");
        product.add("B");
        product.add("C");
        product.add("D");
        product.add("E");
        product.add("F");
    }

    @Override
    public Product getResult() {
        return product;
    }
}

class Builder2 extends Builder{
    Product product = new Product();

    @Override
    public void BuildPart() {
        product.add("A");
        product.add("B");
        product.add("C");
    }

    @Override
    public Product getResult() {
        return product;
    }
}

class Product{
    List<String> parts = new ArrayList<>();

    public void add(String part){
        parts.add(part);
    }

    public void show(){
        System.out.println("产品的组成:");
        for (String s : parts){
            System.out.print(s + " ");
        }
        System.out.println("\n");
    }
}

五、Prototype(原型)

public class Main {
    public static void main(String[] args){
        Product product1 = new Product(2023,5.28);
        System.out.println(product1.getId() + " " + product1.getPrice());

        // Product product2 = new Product(2023,5.28);
        Product product2 = (Product) product1.Clone();
        System.out.println(product2.getId() + " " + product2.getPrice());

    }
}

interface Prototype{
    public Object Clone();
}

class Product implements Prototype {
    private int id;
    private double price;

    public Product() {
    }

    public Product(int id, double price) {
        this.id = id;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public double getPrice() {
        return price;
    }


    @Override
    public Object Clone() {
        Product object = new Product();
        object.id = this.id;
        object.price = this.price;

        return object;
    }

}

六、SingletonPattern(单例模式)

public class SingletonPattern {
    public static void main(String[] args) {
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        Singleton singleton3 = Singleton.getInstance();
    }
}

class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

结构型设计模式

一、Adapter(适配器模式)

public class AdapterPattern {
    public static void main(String[] args){
            USB usb = new Adapter();
            usb.Request();

    }
}

class USB {
    public void Request() {
        System.out.println("USB接口");
    }
}

class Adapter extends USB{
    private TypeC typec = new TypeC();

    @Override
    public void Request() {
        typec.SpecificRequest();
    }

}

class TypeC {
    public void SpecificRequest() {
        System.out.println("Type-C数据线");
    }
}

二、Bridge(桥接)

public class BridgePattern {
    public static void main(String[] args) {
        Product productA = new ProductA();
        Color red = new Red();

        productA.setName("产品A");
        productA.setColor(red);
        productA.Operation();
    }
}

abstract class Product{
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    protected Color color;
    public void setColor(Color color){
        this.color = color;
    }

    public abstract void Operation();
}


class ProductA extends Product{

    @Override
    public void Operation(){
        color.OperationImp(this.getName());
    }
}


interface Color{
    public void OperationImp(String name);
}

class Red implements Color{
    @Override
    public void OperationImp(String name){
        System.out.println(name + "red");
    }
}

class yellow implements Color{
    @Override
    public void OperationImp(String name){
        System.out.println(name + "red");
    }
}

三、Composite(组合)

1、组合模式概念
public class CompositePattern {
    public static void main(String[] args) {
        // 父类名 对象名 = new 子类名();

        AbstractFile folderA = new Folder("folderA");
        folderA.printName();

    }
}

abstract class AbstractFile{ // 抽象组合文件
    protected String name;

    public void printName(){
        System.out.println(name);
    }

}

class Folder extends AbstractFile{ // 文件夹
    public Folder(String name){
        this.name=name;
    }
}

class File extends AbstractFile{ // 文件
    public File(String name){
        this.name=name;
    }
}
2、组合模式添加和删除代码实现
import java.util.ArrayList;
import java.util.List;

public class CompositePattern {
    public static void main(String[] args) {
        // 父类名 对象名 = new 子类名();
        AbstractFile root = new Folder("root");

        AbstractFile folderA = new Folder("folderA");
        AbstractFile fileB = new Folder("fileB");
        folderA.printName();

        System.out.println(root.Add(folderA));
        System.out.println(root.Add(fileB));

        System.out.println(root.Remove(fileB));
        System.out.println(root.Remove(fileB));

    }
}

abstract class AbstractFile{ // 抽象组合文件
    protected String name;

    public void printName(){
        System.out.println(name);
    }

    public abstract boolean Add(AbstractFile file);
    public abstract boolean Remove(AbstractFile file);
    /*public abstract void Add(AbstractFile file);
    public abstract void Remove(AbstractFile file);
*/
}

class Folder extends AbstractFile{ // 文件夹
    private List<AbstractFile> childList = new ArrayList<AbstractFile>();
    public Folder(String name){
        this.name=name;
    }

    @Override
    /*public void Add(AbstractFile file){
        childList.add(file);
    }*/
    public boolean Add(AbstractFile file){
        return childList.add(file);
    }

    @Override
    /*public void Remove(AbstractFile file){
        childList.remove(file);
    }*/
    public boolean Remove(AbstractFile file){
        return childList.remove(file);
    }
}

class File extends AbstractFile{ // 文件
    public File(String name){
        this.name=name;
    }

    @Override
    /*public void Add(AbstractFile file){
        return;
    }*/

    public boolean Add(AbstractFile file){
        return false;
    }
    @Override
   /* public void Remove(AbstractFile file){
        return;
    }*/
    public boolean Remove(AbstractFile file){
        return false;
    }
}
3、组合模式遍历代码实现
import java.util.ArrayList;
import java.util.List;

public class CompositePattern {
    public static void main(String[] args) {
        // 父类名 对象名 = new 子类名();
        AbstractFile root = new Folder("root");

        AbstractFile folderA = new Folder("folderA");
        AbstractFile folderB = new Folder("folderB");

        AbstractFile fileC = new Folder("fileC");
        AbstractFile fileD = new Folder("fileD");
        AbstractFile fileE = new Folder("fileE");

        root.Add(folderA);
        root.Add(folderB);
        root.Add(fileC);

        folderA.Add(fileD);
        folderA.Add(fileE);

        print(root);

        /*folderA.printName();
        System.out.println(root.Add(folderA));
        System.out.println(root.Add(fileB));

        System.out.println(root.Remove(fileB));
        System.out.println(root.Remove(fileB));*/

    }

    static void print(AbstractFile file){
        file.printName();

        List<AbstractFile> childrenList = file.getChildren();
        if (childrenList == null) return;

        // for(对象类型 对象名 : 遍历对象)
        for (AbstractFile children : childrenList){
            // children.printName();
            print(children);
        }
    }
}

abstract class AbstractFile{ // 抽象组合文件
    protected String name;

    public void printName(){
        System.out.println(name);
    }

    public abstract boolean Add(AbstractFile file);
    public abstract boolean Remove(AbstractFile file);
    public abstract List<AbstractFile> getChildren();
    /*public abstract void Add(AbstractFile file);
    public abstract void Remove(AbstractFile file);
*/
}

class Folder extends AbstractFile{ // 文件夹
    private List<AbstractFile> childList = new ArrayList<AbstractFile>();
    public Folder(String name){
        this.name=name;
    }

    @Override
    /*public void Add(AbstractFile file){
        childList.add(file);
    }*/
    public boolean Add(AbstractFile file){
        return childList.add(file);
    }

    @Override
    /*public void Remove(AbstractFile file){
        childList.remove(file);
    }*/
    public boolean Remove(AbstractFile file){
        return childList.remove(file);
    }

    @Override
    public List<AbstractFile> getChildren() {
        return childList;
    }

}

class File extends AbstractFile{ // 文件
    public File(String name){
        this.name=name;
    }

    @Override
    /*public void Add(AbstractFile file){
        return;
    }*/

    public boolean Add(AbstractFile file){
        return false;
    }
    @Override
   /* public void Remove(AbstractFile file){
        return;
    }*/
    public boolean Remove(AbstractFile file){
        return false;
    }

    @Override
    public List<AbstractFile> getChildren() {
        return null;
    }
}

四、Decorator(装饰器)

public class DecoratorPattern {
    public static void main(String[] args) {
        Person zhangsan = new Student("张三");
        zhangsan = new DecoratorA(zhangsan);
        zhangsan = new DecoratorB(zhangsan);
        zhangsan.Operation();

        System.out.println("\n=====我是分割线=====");

        // 对象链
        Person lisi = new DecoratorB(new DecoratorA(new Student("李四")));
        lisi.Operation();

        // 父类名 对象名 = new 对象名();
        // Decorator decoratorA  = new DecoratorA(zhangsan);
        // Person decoratorA  = new DecoratorA(zhangsan);



    }
}

abstract class Decorator extends Person{ // 装饰器
    protected Person person;

}

class DecoratorA extends Decorator {
    public DecoratorA(Person person){
        this.person = person;
    }

    @Override
    public void Operation(){ // 职责
        person.Operation(); // 原本的职责
        System.out.print("写作业 ");

    }
}

class DecoratorB extends Decorator {
    public DecoratorB(Person person){
        this.person = person;
    }

    @Override
    public void Operation(){ // 职责
        person.Operation(); // 原本的职责
        System.out.print("考试 ");

    }
}

abstract class Person{
    protected String name;

    public abstract void Operation(); // 职责

}

class Student extends Person{
    public Student(String name){
        this.name = name;
    }

    @Override
    public void Operation(){
        System.out.print(name + "的职责:学习 ");
    }

}

五、Flyweight(享元模式)

1、黑白棋
public class FlyWeightPattern {
    public static void main(String[] args) {
        PieceFactory factory = new PieceFactory();

        Piece whitePiece1 = factory.getPiece(0);
        System.out.println(whitePiece1);
        whitePiece1.draw(10,10);

        Piece whitePiece2 = factory.getPiece(0);
        System.out.println(whitePiece2);
        whitePiece1.draw(20,20);

        Piece whitePiece3 = factory.getPiece(1);
        System.out.println(whitePiece3);

        Piece whitePiece4 = factory.getPiece(1);
        System.out.println(whitePiece4);

    }
}

class PieceFactory {
    private Piece[] pieces = {new WhitePiece(), new BlackPiece()};

    public Piece getPiece(int key){
        if (key==0) return pieces[0];
        else return pieces[1];
    }
}

abstract class Piece{ // 棋子
    protected String color;

    public abstract void draw(int x,int y);
}

class WhitePiece extends Piece{ // 白棋
    public WhitePiece(){ // 构造器
        this.color = "white";
    }

    public void draw(int x,int y){
        System.out.println("draw a color " + color + " piece x" + x + "y: " + y);
    }

}

class BlackPiece extends Piece{ // 黑棋
    public BlackPiece(){ // 构造器
        this.color = "black";
    }

    public void draw(int x,int y){
        System.out.println("draw a color " + color + " piece x" + x + "y: " + y);
    }
}
2、图形
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class FlyWeightPattern {
    public static void main(String[] args) {
        ShapeFactory factory = new ShapeFactory();

        Random random = new Random();
        String[] colors = {"red", "blue", "green", "white", "black"};

        for (int i = 0; i < 10; i++) {
            int x = random.nextInt(colors.length); // [0 ~ n-1]
            Shape shape = factory.getShape(colors[x]);

            System.out.println("第" + i + "个园:");
            shape.draw(random.nextInt(2023), random.nextInt(528));
        }
    }
}

class ShapeFactory {
    private Map<String,Shape> map = new HashMap<String,Shape>();

    public Shape getShape(String key){
        /*if (map.containsKey(key)){
            return map.get(key); // 根据key值获取对应的value
        } else {
            Shape shape = new Circle(key);
            map.put(key,shape); // 将key的值插入到shape中
            return shape;
            // return map.get(key);
        }*/

        /*if (map.containsKey(key)){
        } else {
            Shape shape = new Circle(key);
            map.put(key,shape);
            //return shape;
        }*/

        if (!map.containsKey(key)){
            map.put(key,new Circle(key));
            System.out.println("create color: " + key + "circle");
        }
         return map.get(key);
    }
}

abstract class Shape { // 图形
    protected String color;

    public abstract void draw(int x,int y);

}

class Circle extends Shape {
    public Circle(String color){
        this.color = color;
    }

    @Override
    public void draw(int x, int y){
        System.out.println("draw a color: " + color + " circle x: " + x + " y: " + y);
    }

}

六、Facade(外观模式)

public class FacadePattern {
    public static void main(String[] args) {
        Facade facade = new Facade();

        facade.methodA();
        facade.methodB();
        facade.methodC();
    }
}

class Facade { // 外观
    SubSystemOne subSystemOne;
    SubSystemTwo subSystemTwo;
    SubSystemThree subSystemThree;

    public Facade() {
        subSystemOne = new SubSystemOne();
        subSystemTwo = new SubSystemTwo();
        subSystemThree = new SubSystemThree();
    }

    public void methodA() {
        subSystemOne.methodOne();
    }

    public void methodB() {
        subSystemTwo.methodTwo();
    }

    public void methodC() {
        subSystemThree.methodThree();
    }
}

class SubSystemOne { // 子系统1
    public void methodOne() {
        System.out.println("执行子系统一的功能");
    }
}

class SubSystemTwo { // 子系统2
    public void methodTwo() {
        System.out.println("执行子系统二的功能");
    }
}

class SubSystemThree { // 子系统3
    public void methodThree() {
        System.out.println("执行子系统三的功能");
    }
}

七、Proxy(代理)

public class ProxyPattern {
    public static void main(String[] args) {
        RealSubject realSubject = new RealSubject();
        Proxy proxy = new Proxy(realSubject);

        proxy.buy();
    }
}

interface Subject {
    public void buy();
}

class Proxy implements Subject {
    protected RealSubject realSubject;

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

    @Override
    public void buy() {
        System.out.println("办理购买前的手续");
        realSubject.buy(); // 付钱
        System.out.println("办理购买后的手续");
    }
}

class RealSubject implements Subject {

    @Override
    public void buy() {
        System.out.println("付钱");
    }
}

行为型设计模式

一、Command(命令模式)

public class CommandPattern {
    public static void main(String[] args) {
        Tv tv = new Tv(); // 接收者 对象 电视剧

        Command onCommand = new OnCommand(tv); // 命令对象 开机命令
        Command offCommand = new OffCommand(tv); // 命令对象 关机命令

        Invoker invoker = new Invoker(); // 请求者
        invoker.setCommand(onCommand); // 给请求者设置 开机 命令
        invoker.call(); // 请求者去请求命令

        System.out.println("=================================");

        invoker.setCommand(offCommand); // 给请求者设置 关机命令
        invoker.call(); // 请求者去请求命令

    }
}

class Invoker { // 请求者
    private Command command; //命令
    public void setCommand(Command command){ // 设置请求者 的 的请求的命令
        this.command = command;
    }

    public void call() {
        command.Execute();
    }
}

interface Command { // 命令接口
    public void Execute(); // 执行命令
}

class OnCommand implements Command{ // 开机命令
    private Tv tv;

    public OnCommand(Tv tv){
        this.tv = tv;
    }

    @Override
    public void Execute(){
        tv.OnAction();
    }
}

class OffCommand implements Command{ // 开机命令
    private Tv tv;

    public OffCommand(Tv tv){
        this.tv = tv;
    }

    @Override
    public void Execute(){
        tv.OffAction();
    }
}

class Tv { // 接收者对象
    public void OnAction(){ // 开机行为
        System.out.println("电视机开机了...");
    }

    public void OffAction(){ // 关机行为
        System.out.println("电视机关机了...");
    }
}

二、Observer(观察者模式)

import java.util.ArrayList;
import java.util.List;

public class ObserverPattern {
    public static void main(String[] args) {
        Subject subjectA = new ConcreateSubject("目标A");

        Observer observerB = new ConcreateObserver("张三",subjectA);
        Observer observerC= new ConcreateObserver("李四",subjectA);
        Observer observerD = new ConcreateObserver("王五",subjectA);

        subjectA.setState("更新了");

        System.out.println("======================================");

        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 ConcreateSubject implements Subject {
    private String name;
    private String state;

    private List<Observer> observerList;

    public ConcreateSubject(String name) {
        state = "未更新";
        this.name = name;
        observerList = new ArrayList<Observer>();
    }

    public void setState(String state){
        this.state = state;

        System.out.println(name + "的状态发生变化,变化后的状态为:" + state);
        Notify();
    }

    public String getState() {
        return state;
    }


    public void Attach(Observer observer){
        observerList.add(observer);
    }

    public void Detach(Observer observer){
        observerList.remove(observer);
    }

    public void Notify(){ // 观察者收到通知 更新下自己的状态
        // for(遍历对象类型 对象名 : 遍历对象)
        for (Observer observer : observerList){
            observer.update();
        }
    }
}

interface Observer { // 观察者接口
    public void update(); // 收到通知 更新观察者状态
}

class ConcreateObserver implements Observer {
    private String name;
    private String state;

    private Subject subject; // 维护一个指向ConcreateSubject对象的引用

    public ConcreateObserver(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);
    }
}

三、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.getState());

    }

}

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());
        }
    }
}

四、Strategy(策略模式)

public class StrategyPattern {
    public static void main(String[] args) {
        Strategy add = new AddStrategy();
        Strategy sub = new Subtrategy();
        Strategy multiply = new MultipyStrategy();

        OperationContext context = new OperationContext(add);
        context.Operation(2023,528);

        context = new OperationContext(sub);
        context.Operation(2023,528);

        context = new OperationContext(multiply);
        context.Operation(2023,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 Subtrategy implements Strategy {

    @Override
    public void TwoNumberOperation(int a,int b) {
        System.out.println(a-b);
    }
}

class MultipyStrategy implements Strategy {

    @Override
    public void TwoNumberOperation(int a,int b) {
        System.out.println(a*b);
    }
}

五、Visitor(访问者模式)

import java.util.ArrayList;
import java.util.List;

public class VisitorPattern {
    public static void main(String[] args) {
        PersonStructure structure = new PersonStructure();

        Visitor visitor1 = new Visitor1();
        System.out.println("访问者1的访问纪录:");
        structure.Accept(visitor1);
        System.out.println("学生年龄的总和:" + ((Visitor1) visitor1).getStudentAgeSum() +" 老师年龄的总和:" + ((Visitor1) visitor1).getTeacherAgeSum());

        System.out.println("============================");

        Visitor2 visitor2 = new Visitor2();
        System.out.println("访问者2的访问纪录:");
        structure.Accept(visitor2);
        System.out.println("学生的最高成绩:" + ((Visitor2) visitor2).getMaxScore() +" 老师的最高工龄:" + ((Visitor2) 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) { // 访问者2
        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<>();

    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 (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 void setName(){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public void setAge(){
        this.age = age;
    }

    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 void setWorkYear(){
        this.workYear = workYear;
    }

    public int getWorkYear(){
        return workYear;
    }

    @Override
    public void Accept(Visitor visitor) {
        visitor.visitTeacher(this);
    }
}

六、Mediator(中介者模式)

import java.util.ArrayList;
import java.util.List;

public class MediatorPattern {
    public static void main(String[] args) {
        ConcreteMediator mediator = new ConcreteMediator(); // 定义一个中介者

        Colleague1 colleague1 = new Colleague1(mediator);
        Colleague2 colleague2 = new Colleague2(mediator);

        mediator.sendMessage1(colleague1);
        mediator.sendMessage2(colleague2);

        colleague1.sendMessage("软考加油");
        colleague2.sendMessage("祝大家考试顺利通过");
    }
}

abstract class Colleague { // 同事
    protected Mediator mediator;
}

class Colleague1 extends Colleague { // 同事1
    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 { // 同事2
    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;

    /* 多个同事的时候
    List<Colleague> list = new ArrayList<>();

    public void Add(Colleague colleague){
        list.add(colleague);
    }*/

    public void sendMessage1(Colleague1 colleague1){
        this.colleague1 = colleague1;
    }

    public void sendMessage2(Colleague2 colleague2){
        this.colleague2 = colleague2;
    }

    public void sendMessage(String message,Colleague colleague){
        if (colleague == colleague1){
            colleague2.Notify(message); // 让同事2收到信息
        } else{
            colleague1.Notify(message); // 让同事1收到信息
        }
    }
}

七、Chain of Responsibility(责任链)

public class ChainOfResponsponsibilityPattern {
    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.HandleRequest(30);

    }
}

abstract class Handler {
    protected Handler next;

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

    public abstract void HandleRequest(int request); // request 请假天数
}

class FuDaoYuan extends Handler { // <=7 审批

    @Override
    public void HandleRequest(int request) {
        if (request <=7) {
            System.out.println("辅导员审批通过");
        }else {
            if (next != null){
                next.HandleRequest(request);
            } else {
                System.out.println("无法审批");
            }
        }
    }
}

class YuanZhang extends Handler { // <=15 审批

    @Override
    public void HandleRequest(int request) {
        if (request <=15) {
            System.out.println("院长审批通过");
        }else {
            if (next != null){
                next.HandleRequest(request);
            } else {
                System.out.println("无法审批");
            }
        }
    }
}

class XiaoZhang extends Handler { // <=15 审批

    @Override
    public void HandleRequest(int request) {
        if (request <=30) {
            System.out.println("校长审批通过");
        }else {
            if (next != null){
                next.HandleRequest(request);
            } else {
                System.out.println("无法审批");
            }
        }
    }
}

八、Interpreter(解释器)

import java.util.HashSet;
import java.util.Set;

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区的程序员");
    }
}

class Context {
    private String[] regions = {"A区","B区","C区"}; // 上下文无关
    private String[] persons = {"开发人员","测试人员","调试人员"}; // 上下文无关

    private NonterminalExpression nonterminal; //非终结符

    public Context(){
        TerminalExpression region = new TerminalExpression(regions); // 定义两个终结符的解释器
        TerminalExpression person = new TerminalExpression(persons); // 定义两个终结符的解释器
        nonterminal = new NonterminalExpression(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 TerminalExpression implements Expression { // 终结符解释器
    private Set<String> set = new HashSet<>();

    public TerminalExpression(String[] data){
        for (String str : data) {
            set.add(str); // 将终结符添加到解释器中去
        }
    }

    @Override
    public boolean Interpret(String info) {
        return set.contains(info); // contains 是否包含指定字符或字符串
    }
}

class NonterminalExpression implements Expression {
    private TerminalExpression region;
    private TerminalExpression person;

    public NonterminalExpression(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]);
    }
}

九、Iterator(迭代器)

package demo;

import java.util.ArrayList;
import java.util.List;

public class IteratorPattern {
    public static void main(String[] args) {
        // List<Book> bookList = new ArrayList<>();

        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(); // 强制转换 next 是 Object类型
            System.out.println(book.getName() + " " + book.getPrice());
        }

        /*for(int i = 0; i < 4; i++){
            bookList.add(new Book(books[i],prices[i]));
        }

        for (int i = 0; i < bookList.size(); i++) {
            Book book = bookList.get(i);
            System.out.println(book.getName() + " " + book.getPrice());
        }

        System.out.println("==================");

        for (Book book : bookList) {
            System.out.println(book.getName() + " " + book.getPrice());
        }

        System.out.println("===================");

        Iterator iterator = bookList.iterator();
        while (iterator.hasNext()){ // 判断是否还有下一个元素
            Book book = (Book)iterator.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<>();

    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 void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

十、Memeto(备忘录)

import java.util.ArrayList;
import java.util.List;

public class MementoPattern {
    public static void main(String[] args) {
        Caretaker caretaker =  new Caretaker();
        Originator originator = new Originator();

        originator.setState("1024"); // 原发器设置一个状态
        Memento backup1 = originator.creatrMemento(); // 创建一个备忘录,并将原发起的状态传入备忘录
        caretaker.addMemento(backup1); // 管理员将备忘录加入到备忘录集合

        originator.setState("2048");
        Memento backup2 = originator.creatrMemento();
        caretaker.addMemento(backup2);

        originator.setState("4096");
        Memento backup3 = originator.creatrMemento();
        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 creatrMemento() {
        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);
        } else {
            return null;
        }

    }

    public void showMemento(){
        int cnt = 1;

        for (Memento memento : mementoList) {
            System.out.println("第" + cnt + "次备份,状态为:" + memento.getState());
            cnt++;
        }


    }

}

十一、Template Method(模板方法)

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("批改作业 打分数");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值