GOF23设计模式

创建型模型

一、单例模式

1、单例模式的类型

1)饿汉式(调用效率高,不能延时加载)

package com.bjsxt.test;
//懒汉式单例模式
public class SingletDemon01 {
    //类初始化时,立即加载类的对象(加载类时,线程天然安全)
   private static SingletDemon01 instance=new SingletDemon01();
   private SingletDemon01(){}
    public static SingletDemon01 getInstance() {
        return instance;
    }
}

2)懒汉式(调用效率不高,可以延时加载)

package com.bjsxt.test;

public class SingletDemon02 {
    private static SingletDemon02 instance;
    private SingletDemon02(){}

    public static synchronized SingletDemon02 getInstance() {
        if(null==instance){
            instance=new SingletDemon02();
        }
        return instance;
    }
}

3)双重检测式(不建议使用)

4)静态内部类式(调用效率高,可延时加载)

package com.bjsxt.test;

public class SingletDemon04 {
    private static class SingletonClassInstance{
        private static final SingletDemon04 instance=new SingletDemon04();
    }
    private SingletDemon04(){}
    public static SingletDemon04 getInstance(){
        return SingletonClassInstance.instance;

    }
}

5)枚举式(调用效率高,不能延时加载,天然的防止反射和反序列化漏洞)

package com.bjsxt.test;

public enum SingletDemon05 {
    INSTANCE;
    //添加自己需要的操作
    public void SingletOperation(){}


}

要点总结:

占用资源少,不需要延时加载:枚举>饿汉

占用资源大,需要延时加载:静态内部类>懒汉

2、单例模式的反射和反序列化漏洞及解决方案

1)反射

package com.bjsxt.test;

import java.lang.reflect.Constructor;

public class Client {
    public static void main(String[] args) throws Exception {
        //通过反射调用私有构造器
        Class<SingletonDemo06> clazz=(Class<SingletonDemo06>)Class.forName("com.bjsxt.test.SingletonDemo06");
        Constructor<SingletonDemo06> c=clazz.getDeclaredConstructor(null);
        c.setAccessible(true);
        SingletonDemo06 s1=c.newInstance();
        SingletonDemo06 s2=c.newInstance();
        System.out.println(s1);
        System.out.println(s2);
        
    }

}

package com.bjsxt.test;
//基于懒汉式的防止反射单例模式
public class SingletonDemo06 {
    private static SingletonDemo06 instance;

    private SingletonDemo06() {
        if(instance!=null){
            throw new RuntimeException();
        }
    }

    public static synchronized SingletonDemo06 getInstance() {
        if (null == instance) {
            instance = new SingletonDemo06();
        }
        return instance;
    }
}

2)反序列化

package com.bjsxt.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

public class Client {
    public static void main(String[] args) throws Exception {
        SingletonDemo06 s1=SingletonDemo06.getInstance();
        SingletonDemo06 s2=SingletonDemo06.getInstance();
        System.out.println(s1);
        System.out.println(s2);
        //通过反序列化的方式构建多个对象
        FileOutputStream fos=new FileOutputStream("d:/a.txt");
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        oos.writeObject(s1);
        oos.close();
        fos.close();
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("d:/a.txt"));
        SingletonDemo06 s3=(SingletonDemo06)ois.readObject();
        System.out.println(s3);

    }
}
package com.bjsxt.test;

import java.io.ObjectStreamException;
import java.io.Serializable;

//基于懒汉式的反序列化单例模式
public class SingletonDemo06 implements Serializable {
    private static SingletonDemo06 instance;

    private SingletonDemo06() {
        if(instance!=null){
            throw new RuntimeException();
        }
    }

    public static synchronized SingletonDemo06 getInstance() {
        if (null == instance) {
            instance = new SingletonDemo06();
        }
        return instance;
    }
    //反序列化
    private Object readResolve() throws ObjectStreamException{
        return  instance;
    }
}

二、工厂模式

1、分类

package com.bjsxt.test;

public interface Car {
    void run();

}
package com.bjsxt.test;

public class Audi implements Car {
    @Override
    public void run() {
        System.out.println("奥迪在跑");
    }
}

 

package com.bjsxt.test;

public class Byd implements Car{
    @Override
    public void run() {
        System.out.println("比亚迪再跑");
    }
}

1)简单工厂模式

package com.bjsxt.test;

public  class CarFactory {
    public static Car creatCar(String type){
        if("奥迪".equals(type)){
            return new Audi();
        }else if("比亚迪".equals(type)){
            return new Byd();
        }else{
            return null;
        }
    }
package com.bjsxt.test;

public class Client01 {
    public static void main(String[] args) {
        Car c1=CarFactory.creatCar("奥迪");
        Car c2=CarFactory.creatCar("比亚迪");
        c1.run();
        c2.run();
    }
}

2)工厂方法模式

package com.bjsxt.test.factorymethod;

public interface CarFactory1 {
    Car creatCar();
}
package com.bjsxt.test.factorymethod;

public class BydFactory implements CarFactory1{
    @Override
    public Car creatCar() {
        return new Byd();
    }
}
package com.bjsxt.test.factorymethod;

public class AudiFactory implements CarFactory1{
    @Override
    public Car creatCar() {
        return new Audi();
    }
}

 

package com.bjsxt.test.factorymethod;

public class Client02 {
    public static void main(String[] args) {
        Car car1=new AudiFactory().creatCar();
        Car car2=new BydFactory().creatCar();
        car1.run();
        car2.run();
    }

}

3)抽象工厂模式

实现多个接口的方法

4)建造者模式

package com.bjsxt.test.builder;

public class AirShip {
    private OrbitalModule orbitalModule;
    private Engine engine;
    private EscapeTower escapeTower;

    public AirShip() {
    }

    public OrbitalModule getOrbitalModule() {
        return orbitalModule;
    }

    public void setOrbitalModule(OrbitalModule orbitalModule) {
        this.orbitalModule = orbitalModule;
    }

    public Engine getEngine() {
        return engine;
    }

    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    public EscapeTower getEscapeTower() {
        return escapeTower;
    }

    public void setEscapeTower(EscapeTower escapeTower) {
        this.escapeTower = escapeTower;
    }

    public AirShip(OrbitalModule orbitalModule, Engine engine, EscapeTower escapeTower) {
        this.orbitalModule = orbitalModule;
        this.engine = engine;
        this.escapeTower = escapeTower;
    }
}
class OrbitalModule{
    private String name;

    public OrbitalModule(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public Engine(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public EscapeTower(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.bjsxt.test.builder;

public interface AirShipBuilder {
    OrbitalModule buildOrbitalModule();
    Engine buildEngine();
    EscapeTower buildEscapeTower();
}

 

package com.bjsxt.test.builder;

public class SxtAirShipBuilder implements AirShipBuilder {

    @Override
    public OrbitalModule buildOrbitalModule() {
        return new OrbitalModule("尚学堂牌轨道舱");
    }

    @Override
    public Engine buildEngine() {
        return new Engine("尚学堂牌发动机");
    }

    @Override
    public EscapeTower buildEscapeTower() {
        return new EscapeTower("尚学堂牌逃逸舱");
    }
}
package com.bjsxt.test.builder;

public interface AirShipDirecter {
    AirShip directAirShip();
}
package com.bjsxt.test.builder;

public class SxtAirShipDirector implements AirShipDirecter{
    private AirShipBuilder builder;

    public SxtAirShipDirector(AirShipBuilder builder) {
        this.builder = builder;
    }

    @Override
    public AirShip directAirShip() {
        Engine en=builder.buildEngine();
        OrbitalModule o=builder.buildOrbitalModule();
        EscapeTower e=builder.buildEscapeTower();
        AirShip ship=new AirShip();
        ship.setEngine(en);
        ship.setOrbitalModule(o);
        ship.setEscapeTower(e);
        return ship;
    }
}
package com.bjsxt.test.builder;
public class Client03 {
    public static void main(String[] args) {
        AirShipDirecter directer=new SxtAirShipDirector(new SxtAirShipBuilder());
        AirShip ship=directer.directAirShip();
        System.out.println(ship.getEngine().getName());
    }
}

5)原型模式

<1>浅克隆

package com.bjsxt.test.prototype;
import java.util.Date;
public class Sheep implements Cloneable {
    private String name;
    private Date birthday;

        @Override
        protected Object clone()throws CloneNotSupportedException{
        Object obj=super.clone();
        return obj;
    }

    public Sheep(String name, Date birthday) {
        this.name = name;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Sheep() {
    }
}
package com.bjsxt.test.prototype;

import java.util.Date;

public class Client04 {
    public static void main(String[] args) throws CloneNotSupportedException {
        Date d=new Date(91284763L);
        Sheep s1=new Sheep("少莉",d);
        System.out.println(s1);
        System.out.println(s1.getName()+"-->"+s1.getBirthday());
        d.setTime(19287300948832L);
        Sheep s2=(Sheep) s1.clone();
        System.out.println(s1.getName()+"-->"+s1.getBirthday());
        s2.setName("多莉");
        System.out.println(s2);
        System.out.println(s2.getName()+"-->"+s2.getBirthday());

    }
}

运行结果

com.bjsxt.test.prototype.Sheep@1b6d3586
少莉-->Fri Jan 02 09:21:24 CST 1970
少莉-->Sat Mar 10 23:35:48 CST 2581
com.bjsxt.test.prototype.Sheep@14ae5a5
多莉-->Sat Mar 10 23:35:48 CST 2581

<2>深克隆

package com.bjsxt.test.prototype;
import java.util.Date;
public class Sheep implements Cloneable {
    private String name;
    private Date birthday;

        @Override
        protected Object clone()throws CloneNotSupportedException{
        Object obj=super.clone();
        //加入下面两行
        Sheep s=(Sheep) obj;
        s.birthday=(Date) this.birthday.clone();
        return obj;
    }

    public Sheep(String name, Date birthday) {
        this.name = name;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Sheep() {
    }
}

 

package com.bjsxt.test.prototype;

import java.util.Date;

public class Client04 {
    public static void main(String[] args) throws CloneNotSupportedException {
        Date d=new Date(91284763L);
        Sheep s1=new Sheep("少莉",d);
        Sheep s2=(Sheep) s1.clone();
        System.out.println(s1);
        System.out.println(s1.getName()+"-->"+s1.getBirthday());
        d.setTime(19287300948832L);
        System.out.println(s1.getName()+"-->"+s1.getBirthday());
        s2.setName("多莉");
        System.out.println(s2);
        System.out.println(s2.getName()+"-->"+s2.getBirthday());

    }
}

运行结果

com.bjsxt.test.prototype.Sheep@1b6d3586
少莉-->Fri Jan 02 09:21:24 CST 1970
少莉-->Sat Mar 10 23:35:48 CST 2581
com.bjsxt.test.prototype.Sheep@14ae5a5
多莉-->Fri Jan 02 09:21:24 CST 1970

反序列化 深克隆

package com.bjsxt.test.prototype;
import java.io.Serializable;
import java.util.Date;
public class Sheep implements Cloneable, Serializable {
    private String name;
    private Date birthday;

        @Override
        protected Object clone()throws CloneNotSupportedException{
        Object obj=super.clone();
        //加入下面两行
       // Sheep s=(Sheep) obj;
        //s.birthday=(Date) this.birthday.clone();
        return obj;
    }

    public Sheep(String name, Date birthday) {
        this.name = name;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Sheep() {
    }
}

要点:实现Serializable接口

package com.bjsxt.test.prototype;
import java.io.*;
import java.util.Date;

public class Client05 {
    public static void main(String[] args) throws Exception {
        Date d=new Date(91284763L);
        Sheep s3 =new Sheep("少莉",d);
        System.out.println(s3);
        System.out.println(s3.getName()+"-->"+s3.getBirthday());
        //Sheep s2=(Sheep) s1.clone();
        //使用序列化和反序列化实现深复制
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        ObjectOutputStream oos=new ObjectOutputStream(baos);
        oos.writeObject(s3);
        byte[] bytes=baos.toByteArray();
        ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
        ObjectInputStream  ois=new ObjectInputStream(bais);
        Sheep s4=(Sheep)ois.readObject();

        d.setTime(19287300948832L);
        System.out.println(s3.getName()+"-->"+s3.getBirthday());
        s4.setName("多莉");
        System.out.println(s4);
        System.out.println(s4.getName()+"-->"+s4.getBirthday());

    }

}

运行结果

com.bjsxt.test.prototype.Sheep@1b6d3586
少莉-->Fri Jan 02 09:21:24 CST 1970
少莉-->Sat Mar 10 23:35:48 CST 2581
com.bjsxt.test.prototype.Sheep@30dae81
多莉-->Fri Jan 02 09:21:24 CST 1970

 结构型模型

一、适配器模式

package com.bjsxt.test.adapter;
//键盘
public class Adaptee {
    public void request(){
        System.out.println("键盘可以打字");
    }
}
package com.bjsxt.test.adapter;
//相当于笔记本
public class Client {
    public void test1(Target t){
        t.handle();
    }

    public static void main(String[] args) {
        Client c=new Client();
        Adaptee a=new Adaptee();
        Target t=new Adapter2(a);
        c.test1(t);
    }
}
package com.bjsxt.test.adapter;
//USB接口
public interface Target {
    void handle();
}
package com.bjsxt.test.adapter;
//适配器(类适配器方法)
public class Adapter extends Adaptee implements Target{
    @Override
    public void handle() {
        super.request();

    }
}
package com.bjsxt.test.adapter;

public class Adapter2 implements Target {
    private Adaptee adaptee;
    @Override
    public void handle() {
        adaptee.request();
    }

    public Adapter2(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
}

二、代理模式

1、静态代理

package com.bjsxt.test.proxy.staticProxy;

public interface Star {
    void confer();
    void signContract();
    void bookTicket();
    void sing();
    void  collectMoney();

}
package com.bjsxt.test.proxy.staticProxy;

public class RealStar implements Star {
    @Override
    public void confer() {
        System.out.println("RealStar.confer");
    }

    @Override
    public void signContract() {
        System.out.println("RealStar.signContract");
    }

    @Override
    public void bookTicket() {
        System.out.println("RealStar.bookTicket");
    }

    @Override
    public void sing() {
        System.out.println("RealStar(周杰伦本人).sing");
    }

    @Override
    public void collectMoney() {
        System.out.println("RealStar.collectMoney");
    }
}
package com.bjsxt.test.proxy.staticProxy;

public class ProxyStar implements Star{
    private Star star;

    public ProxyStar(Star star) {
        this.star = star;
    }

    @Override
    public void confer() {
        System.out.println("ProxyStar.confer");
    }

    @Override
    public void signContract() {
        System.out.println("ProxyStar.signContract");
    }

    @Override
    public void bookTicket() {
        System.out.println("ProxyStar.bookTicket");
    }

    @Override
    public void sing() {
        this.star.sing();
    }

    @Override
    public void collectMoney() {
        System.out.println("ProxyStar.collectMoney");
    }
}
package com.bjsxt.test.proxy.staticProxy;

public class Client {
    public static void main(String[] args) {
        Star real=new RealStar();
        Star proxy=new ProxyStar(real);
        proxy.confer();
        proxy.signContract();
        proxy.bookTicket();
        proxy.sing();
        proxy.collectMoney();
    }
}

运行结果

ProxyStar.confer
ProxyStar.signContract
ProxyStar.bookTicket
RealStar(周杰伦本人).sing
ProxyStar.collectMoney

2、动态代理

package com.bjsxt.test.DynamicProxy;

public interface Star {
    void confer();
    void signContract();
    void bookTicket();
    void sing();
    void  collectMoney();

}

 

package com.bjsxt.test.DynamicProxy;



public class RealStar implements Star {
    @Override
    public void confer() {
        System.out.println("RealStar.confer");
    }

    @Override
    public void signContract() {
        System.out.println("RealStar.signContract");
    }

    @Override
    public void bookTicket() {
        System.out.println("RealStar.bookTicket");
    }

    @Override
    public void sing() {
        System.out.println("RealStar(周杰伦本人).sing");
    }

    @Override
    public void collectMoney() {
        System.out.println("RealStar.collectMoney");
    }
}
package com.bjsxt.test.DynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class StarHandler implements InvocationHandler {
    Star realStar;

    public StarHandler(Star realStar) {
        this.realStar = realStar;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object object=null;
        System.out.println("真正的方法执行前");
        System.out.println("面谈、签合同、订机票");
        if(method.getName().equals("sing")){
            object=method.invoke(realStar,args);
        }
        System.out.println("真正的方法执行后");
        System.out.println("收尾款");
        return object;
    }
}
package com.bjsxt.test.DynamicProxy;

import java.lang.reflect.Proxy;

public class Client {
    public static void main(String[] args) {
        Star realStar=new RealStar();
        StarHandler handler=new StarHandler(realStar);
        Star proxy=(Star) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(),
        new Class[]{Star.class},handler);
        proxy.sing();
    }
}

运行结果

真正的方法执行前
面谈、签合同、订机票
RealStar(周杰伦本人).sing
真正的方法执行后
收尾款

三、桥接模式

package com.bjsxt.test.bridge;

public interface Brand {
    void sale();
}
class levono implements Brand{
    @Override
    public void sale() {
        System.out.println("销售联想电脑");
    }
}
class bell implements Brand{
    @Override
    public void sale() {
        System.out.println("销售贝尔电脑");
    }
}

 

package com.bjsxt.test.bridge;

public class Computer {
    protected Brand brand;

    public Computer(Brand brand) {
        this.brand = brand;
    }
    public  void sale(){
        brand.sale();
    }
}
class Laptop extends Computer{

    public Laptop(Brand brand) {
        super(brand);
    }

    @Override
    public void sale() {
        super.sale();
        System.out.println("销售笔记本");
    }
}
class Ipad extends Computer{

    public Ipad(Brand brand) {
        super(brand);
    }

    @Override
    public void sale() {
        super.sale();
        System.out.println("销售平板电脑");
    }
}
package com.bjsxt.test.bridge;

public class Client {
    public static void main(String[] args) {
        Computer c=new Laptop(new levono());
        c.sale();
    }
}

运行结果

销售联想电脑
销售笔记本

四、组合模式

package com.bjsxt.test.composite;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public interface AbstractFile {
    void killVirus();
}
class ImageFile implements AbstractFile{
    private String name;

    public ImageFile(String name) {
        this.name = name;
    }

    @Override
    public void killVirus() {
        System.out.println("---图像文件"+name+",进行查杀");
    }
}
class TextFile implements AbstractFile{
    private String name;

    public TextFile(String name) {
        this.name = name;
    }

    @Override
    public void killVirus() {
        System.out.println("---文本文件"+name+",进行查杀");
    }
}
class VideoFile implements AbstractFile{
    private String name;

    public VideoFile(String name) {
        this.name = name;
    }

    @Override
    public void killVirus() {
        System.out.println("---视频文件"+name+",进行查杀");
    }
}
class Folder implements AbstractFile{
    private String name;
    private List<AbstractFile> list =new ArrayList<>();

    public Folder(String name) {
        this.name = name;
    }
    public void add(AbstractFile file){
        list.add(file);
    }
    public void remove(AbstractFile file){
        list.remove(file);
    }
    public AbstractFile getChild(int index){
        return list.get(index);
    }
    @Override
    public void killVirus() {
        System.out.println("----文件夹"+name+",进行查杀");
        for(AbstractFile file: list){
            file.killVirus();
        }
    }
}

 

package com.bjsxt.test.composite;

public class Client {
    public static void main(String[] args) {
        Folder f1 =new Folder("我的收藏");
        Folder f2=new Folder("我的喜欢");

        AbstractFile f3= new ImageFile("老高的大头像.jpg");
        AbstractFile f4=new TextFile("Hello.txt");
        AbstractFile f5=new VideoFile("笑傲江湖.avi");
        AbstractFile f6=new VideoFile("神雕侠侣.avi");
        f1.add(f3);
        f1.add(f4);
        f2.add(f5);
        f2.add(f6);
        f1.add(f2);
        f1.killVirus();
    }

}

运行结果

----文件夹我的收藏,进行查杀
---图像文件老高的大头像.jpg,进行查杀
---文本文件Hello.txt,进行查杀
----文件夹我的喜欢,进行查杀
---视频文件笑傲江湖.avi,进行查杀
---视频文件神雕侠侣.avi,进行查杀

五、装饰模式

package com.bjsxt.test.decorator;



//抽象组件
public interface ICar {
    void remove();
}
//具体组件
class Car implements ICar{

    @Override
    public void remove() {
        System.out.println("陆地上跑");
    }
}
//抽象装饰类
class SuperCar implements ICar{
    protected ICar car;

    public SuperCar(ICar car) {
        this.car = car;
    }

    @Override
    public void remove() {
        car.remove();
    }
}

//具体装饰类
class WaterCar extends SuperCar {
    public WaterCar(ICar car) {
        super(car);
    }
    private  void water(){
        System.out.println("水上游");
    }

    @Override
    public void remove() {
        water();
        car.remove();
    }
}
package com.bjsxt.test.decorator;

public class Client {
    public static void main(String[] args) {
        ICar car=new WaterCar(new Car());
        car.remove();
    }
}

运行结果

水上游
陆地上跑

六、外观模式(封装)

七、 享元模式

package com.bjsxt.test.flyweight;
//享元类
public interface ChessFlyWeight {
    void setColor(String color);
    String getColor();
    void display(Coordinate c);
}
class ConcreteChess implements ChessFlyWeight{
    private String color;

    public ConcreteChess(String color) {
        this.color = color;
    }

    @Override
    public void setColor(String color) {
        this.color=color;
    }

    @Override
    public String getColor() {
        return color;
    }

    @Override
    public void display(Coordinate c) {
        System.out.println("棋子的颜色"+color);
        System.out.println("棋子的位置为"+c.getX()+"-->"+c.getY());
    }
}
package com.bjsxt.test.flyweight;
//外部状态的非共享元类
public class Coordinate {
    private int x,y;

    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}

 

import java.util.Map;

//享元工厂类
public class ChessFlyWeightFactory {
    private static Map<String,ChessFlyWeight> map=new HashMap<>();
    public static ChessFlyWeight getChess(String color){
        if(map.get(color)!=null) {
            return  map.get(color);
        }else{
            ChessFlyWeight c=new ConcreteChess(color);
            map.put(color,c);
            return c;
        }
    }
}
package com.bjsxt.test.flyweight;

public class Client {
    public static void main(String[] args) {
        ChessFlyWeight chess1=ChessFlyWeightFactory.getChess("黑色");
        ChessFlyWeight chess2=ChessFlyWeightFactory.getChess("黑色");
        System.out.println(chess1);
        System.out.println(chess2);
        chess1.display(new Coordinate(10,10));
        chess2.display(new Coordinate(20,10));
    }
}

运行结果

com.bjsxt.test.flyweight.ConcreteChess@1b6d3586
com.bjsxt.test.flyweight.ConcreteChess@1b6d3586
棋子的颜色黑色
棋子的位置为10-->10
棋子的颜色黑色
棋子的位置为20-->10

行为模式

一、责任链模式

package com.bjsxt.test.chainOfResb;

public class LeaveRequest {
    private String empName;
    private int leaveDays;
    private  String reason;

    public String getEmpName() {
        return empName;
    }
    public int getLeaveDays() {
        return leaveDays;
    }
    public String getReason() {
        return reason;
    }
    public LeaveRequest(String empName, int leaveDays, String reason) {
        this.empName = empName;
        this.leaveDays = leaveDays;
        this.reason = reason;
    }
}
package com.bjsxt.test.chainOfResb;

public abstract class Leader {
    protected String name;
    protected Leader nextLeader;//责任链的下一个对象

    public Leader(String name) {
        this.name = name;
    }

    public void setNextLeader(Leader nextLeader) {
        this.nextLeader = nextLeader;
    }
    //抽象方法(处理请求业务的核心方法)
    public abstract void handleRequest(LeaveRequest request);
}
package com.bjsxt.test.chainOfResb;

public class Director extends Leader {

    public Director(String name) {
        super(name);
    }

    @Override
    public void handleRequest(LeaveRequest request) {
        if(request.getLeaveDays()<3){
            System.out.println(this.name+"主任审批通过"+request.getEmpName()+"因"+ request.getReason()+"请假"+request.getLeaveDays()+"天");
        }else {
            if(this.nextLeader!=null){
                this.nextLeader.handleRequest(request);
            }
        }
    }
}
package com.bjsxt.test.chainOfResb;

public class Manager extends Leader {

    public Manager(String name) {
        super(name);
    }

    @Override
    public void handleRequest(LeaveRequest request) {
        if(request.getLeaveDays()<10){
            System.out.println(this.name+"经理审批通过"+request.getEmpName()+"因"+ request.getReason()+"请假"+request.getLeaveDays()+"天");
        }else {
            if(this.nextLeader!=null){
                this.nextLeader.handleRequest(request);
            }
        }
    }
}
package com.bjsxt.test.chainOfResb;

public class GeneralManager extends Leader{
    public GeneralManager(String name) {
        super(name);
    }

    @Override
    public void handleRequest(LeaveRequest request) {
        if(request.getLeaveDays()<30){
            System.out.println(this.name+"总经理审批通过"+request.getEmpName()+"因"+ request.getReason()+"请假"+request.getLeaveDays()+"天");
        }else {
            System.out.println("莫非"+request.getEmpName()+"不想干了");
            }
        }
    }
package com.bjsxt.test.chainOfResb;

public class Client {
    public static void main(String[] args) {
        Leader director=new Director("张三");
        Leader manager=new Manager("李四");
        Leader generalManager=new GeneralManager("王五");
        director.setNextLeader(manager);
        manager.setNextLeader(generalManager);
        LeaveRequest leaveRequest =new  LeaveRequest("小王",1,"回家结婚");
        director.handleRequest(leaveRequest);
    }

}

二、迭代器模式

package com.bjsxt.test.iterator;
//自定义的迭代器接口
public interface MyIterator {
    void first();//将游标指向第一个元素
    void next();//将游标指向下一个元素
    boolean hasNext();//判断是否存在下一个元素
    boolean isFirst();
    boolean isLast();
    Object getCurrentObj();//获取当前游标指向的对象
}
package com.bjsxt.test.iterator;

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

//自定义聚合类
public class ConcreteMyAggregate {
    private List<Object> list=new ArrayList<>();


    public MyIterator creatIterater(){
        return new ConcreIterator();
    }

    public void addObject(Object obj){
        this.list.add(obj);
    }
    public void removeObject(Object obj){
        this.list.remove(obj);
    }

    public List<Object> getList() {
        return list;
    }

    public void setList(List<Object> list) {
        this.list = list;
    }
    private class ConcreIterator implements MyIterator{
        private  int cursor;//游标表示标志的位置
        @Override
        public void first() {
            cursor=0;
        }

        @Override
        public void next() {
            if(cursor<list.size()) cursor++;
        }

        @Override
        public boolean hasNext() {
            if(cursor<list.size())return true;
            else return false;
        }

        @Override
        public boolean isFirst() {
            if(cursor==0) return true;
            else  return false;
        }

        @Override
        public boolean isLast() {
            if(cursor==(list.size()-1)) return true;
            else return false;
        }

        @Override
        public Object getCurrentObj() {
            return list.get(cursor);
        }
    }
}
package com.bjsxt.test.iterator;

public class Client {
    public static void main(String[] args) {
        ConcreteMyAggregate cma=new ConcreteMyAggregate();
        cma.addObject("aa");
        cma.addObject("bb");
        cma.addObject("cc");
        MyIterator iter=cma.creatIterater();
        while(iter.hasNext()){
            System.out.println(iter.getCurrentObj());
            iter.next();
        }
    }
}

三、中介者模式

package com.bjsxt.test.mediator;

public interface Mediator {
    void register(String name,Department d);
    void demand(String name);
}
package com.bjsxt.test.mediator;

public interface Department {
    void selfAction();//做本部门的工作
    void outAction();//向总经理发出申请
}
package com.bjsxt.test.mediator;

public class Development implements Department{
    private  Mediator m;

    public Development(Mediator m) {
        this.m = m;
        m.register("development",this);
    }

    @Override
    public void selfAction() {
        System.out.println("专心科研,开发项目");
    }

    @Override
    public void outAction() {
        System.out.println("汇报工作,没钱了,需要资金支持");
        m.demand("finacial");
    }
}
package com.bjsxt.test.mediator;

public class Finacial implements Department{
    private  Mediator m;

    public Finacial(Mediator m) {
        this.m = m;
        m.register("finacial",this);
    }

    @Override
    public void selfAction() {
        System.out.println("数钱");
    }

    @Override
    public void outAction() {
        System.out.println("汇报工作,钱太多了,怎么花");

    }
}
package com.bjsxt.test.mediator;

import java.util.HashMap;
import java.util.Map;

public class President implements Mediator{
    private Map<String,Department> map=new HashMap<String,Department>();
    @Override
    public void register(String dname, Department d) {
        map.put(dname,d);
    }

    @Override
    public void demand(String name) {
        map.get(name).selfAction();
    }
}
package com.bjsxt.test.mediator;

public class Client {
    public static void main(String[] args) {
        Mediator m=new President();
        Development development=new Development(m);
        Finacial finacial=new Finacial(m);
        development.selfAction();
        development.outAction();
    }
}

运行结果

专心科研,开发项目
汇报工作,没钱了,需要资金支持
数钱 

四、命令模式

五、 解释器模式

六、访问者模式

七、策略模式

package com.bjsxt.test.strategy;

public interface Strategy {
    public double getPrice(double standardPrice);
}
package com.bjsxt.test.strategy;

public class NewCustomFewDemand implements Strategy {

    @Override
    public double getPrice(double standardPrice) {
        System.out.println("原价销售");
        return standardPrice;
    }
}
package com.bjsxt.test.strategy;

public class  NewCustomManyDemand  implements  Strategy{
    @Override
    public double getPrice(double standardPrice) {
        System.out.println("打九折");
        return standardPrice*0.9;
    }
}

 

package com.bjsxt.test.strategy;

public class OldCustomFewDemand implements Strategy {
    @Override
    public double getPrice(double standardPrice) {
        System.out.println("打八五折");
        return standardPrice*0.85;
    }
}

 

package com.bjsxt.test.strategy;

public class OldCustomManyDemand implements Strategy{
    @Override
    public double getPrice(double standardPrice) {
        System.out.println("打八折");
        return standardPrice;
    }
}

public class Context {
    private Strategy strategy;


    public Context(Strategy strategy) {
        this.strategy = strategy;

    }

    public void test(double price){
        System.out.println(strategy.getPrice(price));
    }
}
package com.bjsxt.test.strategy;

public class Client {
    public static void main(String[] args) {
        Strategy s =new NewCustomManyDemand();
        new Context(s).test(998);
    }


}

 运行结果

打九折
898.2

 

八、模板方法模式

package com.bjsxt.test.templateMethod;

public abstract class BankTemplateMethod {
    public void takeNumber(){
        System.out.println("排队取号");
    }
    public  abstract void transact();//处理具体的业务
    public  void evaluate(){
        System.out.println("反馈得分");
    }
    public final void process(){
        this.takeNumber();
        this.transact();
        this.evaluate();
    }
}
package com.bjsxt.test.templateMethod;

public class Client {
    public static void main(String[] args) {
        BankTemplateMethod bank= new BankTemplateMethod() {
            @Override
            public void transact() {
                System.out.println("我要存钱");
            }
        };
        bank.process();
    }
}

 结果分析

排队取号
我要存钱
反馈得分

九、状态模式

package com.bjsxt.test.state;

public interface State {
    void handle();
}
package com.bjsxt.test.state;

public class BookedState implements State{
    @Override
    public void handle() {
        System.out.println("房间已预订");
    }
}
package com.bjsxt.test.state;

public class CheckedState implements State{
    @Override
    public void handle() {
        System.out.println("房间已入住");
    }
}

 

package com.bjsxt.test.state;

public class FreeState implements State{
    @Override
    public void handle() {
        System.out.println("房间空闲");

    }
}

 

package com.bjsxt.test.state;

public class Context {
    private State state;

    public void setState(State state) {
        this.state = state;
        state.handle();
    }


}
package com.bjsxt.test.state;

public class Client {
    public static void main(String[] args) {
        State bookedState=new BookedState();
        new Context().setState(bookedState);
    }
}

 运行结果

房间已预订

十、观察者模式

package com.bjsxt.test.observer;

public interface Observer {
    void update (Subject subject);
}
package com.bjsxt.test.observer;

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

public class Subject {
    protected List<Observer> list=new ArrayList<Observer>();
    public void registerObserver(Observer observer){
        list.add(observer);
    }
    public void removeObserver(Observer observer){
        list.remove(observer);
    }
    public  void NotifyAllObserver(){
        for(Observer obs:list){
            obs.update(this);
        }

    }


}
package com.bjsxt.test.observer;

public class ObserverA implements Observer{
    private  int myState;
    @Override
    public void update(Subject subject) {
        myState=((ConcretSubject) subject).getState();
    }

    public int getMyState() {
        return myState;
    }

    public void setMyState(int myState) {
        this.myState = myState;
    }
}
package com.bjsxt.test.observer;

public class ConcretSubject extends Subject {
    private  int state;

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
        //主题对象发生变化,通知所有观察者
        this.NotifyAllObserver();
    }
}
package com.bjsxt.test.observer;

public class Client {
    public static void main(String[] args) {
        //目标对象
        ConcretSubject subject=new ConcretSubject();
        //创建多个观察者
        ObserverA observer1=new ObserverA();
        ObserverA observer2=new ObserverA();
        ObserverA observer3=new ObserverA();
        //将这三个观察者添加到subject对象的观察者队伍中
        subject.registerObserver(observer1);
        subject.registerObserver(observer2);
        subject.registerObserver(observer3);
        //改变subject的状态
        subject.setState(3000);
        //观察者的状态
        System.out.println(observer1.getMyState());
        System.out.println(observer2.getMyState());
        System.out.println(observer3.getMyState());

    }
}

运行结果

3000
3000
3000

使用JDK提供好的类和接口

package com.bjsxt.test.Observer2;

import java.util.Observable;
public class ConcreteSubject extends Observable {
    private int state;
    public void set(int s){
        state=s;
        setChanged();//表示目标对象已经做了更改
        notifyObservers(state);//通知所有的观察者

    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }
}

 

package com.bjsxt.test.Observer2;
import java.util.Observable;
import java.util.Observer;

public class ObserverA implements Observer {
    private  int myState;
    @Override
    public void update(Observable o, Object arg) {
        myState= ((ConcreteSubject)o).getState();
    }

    public int getMyState() {
        return myState;
    }

    public void setMyState(int myState) {
        this.myState = myState;
    }
}
package com.bjsxt.test.Observer2;

public class Client {
    public static void main(String[] args) {
        ConcreteSubject subject=new ConcreteSubject();
        ObserverA observer1=new ObserverA();
        ObserverA observer2=new ObserverA();
        ObserverA observer3=new ObserverA();
        subject.addObserver(observer1);
        subject.addObserver(observer2);
        subject.addObserver(observer3);
        subject.set(2893);
        System.out.println(observer1.getMyState());
        System.out.println(observer2.getMyState());
        System.out.println(observer3.getMyState());
    }
}

 

十一、 备忘录模式

package com.bjsxt.test.memento;

public class EmpMemento {
    private String ename;
    private int age;
    private double salary;
    public  EmpMemento(Emp e){
        ename=e.getEname();
        age=e.getAge();
        salary=e.getSalary();
    }
    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public int getAge() {
        return age;
    }

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

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}
package com.bjsxt.test.memento;
//负责人管理备忘录对象
public class CareTaker {
    private EmpMemento empMemento;

    public EmpMemento getEmpMemento() {
        return empMemento;
    }

    public void setEmpMemento(EmpMemento empMemento) {
        this.empMemento = empMemento;
    }
}
package com.bjsxt.test.memento;

public class Client {
    public static void main(String[] args) {
        CareTaker taker=new CareTaker();
        Emp emp=new Emp("高淇",18,900);
        System.out.println("第一次打印对象:"+emp.getEname()+"-->"+emp.getAge()+"-->"+emp.getSalary());
        taker.setEmpMemento(emp.memento());
        emp.setAge(20);
        emp.setEname("搞起");
        emp.setSalary(240);
        System.out.println("第二次打印对象:"+emp.getEname()+"-->"+emp.getAge()+"-->"+emp.getSalary());
        emp.recovery(taker.getEmpMemento());
        System.out.println("第三次打印对象:"+emp.getEname()+"-->"+emp.getAge()+"-->"+emp.getSalary());

    }
}
package com.bjsxt.test.memento;

public class Emp {
    private String ename;
    private int age;
    private double salary;

    public Emp(String ename, int age, double salary) {
        this.ename = ename;
        this.age = age;
        this.salary = salary;
    }
    //进行备忘操作,并返回备忘录对象
    public EmpMemento memento(){
        return new EmpMemento(this);
    }
    //进行数据恢复,恢复为指定备忘录对象的值
    public void recovery(EmpMemento mmt){
        this.ename=mmt.getEname();
        this.age=mmt.getAge();
        this.salary=mmt.getSalary();

    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public int getAge() {
        return age;
    }

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

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

运行结果

第一次打印对象:高淇-->18-->900.0
第二次打印对象:搞起-->20-->240.0
第三次打印对象:高淇-->18-->900.0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值