设计模式04:装饰器模式、享元模式、命令模式、观察者模式

1.Decorator装饰器模式

 示例代码:

package Decorator09;

/**
 * 装饰器模式
 * 意图:动态的给一个对象添加一些额外的职责。
 * 适用性:
 *      在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责
 *      处理那些可以撤销的职责
 */
public class DecoratorPattern {
    public static void main(String[] args) {
        Person zhangsan = new Student("张三");
        zhangsan.Operation();
        System.out.println("--------------------");
//        DecoratorA decoratorA = new DecoratorA(zhangsan);
//        Person zhangsan = new DecoratorA(zhangsan);
        zhangsan = new DecoratorA(zhangsan);
        zhangsan.Operation();
        System.out.println("--------------------");
        zhangsan = new DecoratorB(zhangsan);
        zhangsan.Operation();


    }
}
//Component
abstract class Person{
    protected String name;
    public abstract void Operation();
}
//ConcreteComponent
class Student extends Person{
    public Student(String name){
        this.name=name;
    }

    @Override
    public void Operation() {
        //职责方法
        System.out.println(name+"的职责:学习");
    }
}
//Decorator
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.println("新增职责:扫地");//新增职责
    }
}
class DecoratorB extends Decorator{

    public DecoratorB(Person person){
        this.person = person;
    }
    @Override
    public void Operation() {
        //职责方法
        person.Operation();//原先的职责
        System.out.println("新增职责:唱歌");//新增职责
    }
}

2.Flyweight享元模式

 

示例代码:

package Flyweight10;

/**
 * 享元模式
 * 意图:运用共享技术有效地支持大量细粒度的对象
 *
 */
public class Flyweight {
    public static void main(String[] args) {
        PieceFactory pieceFactory = new PieceFactory();
        //白棋
        Piece whitePiece1 = pieceFactory.getPiece(0);
        whitePiece1.draw(1,3);
    }
}
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";
    }

    @Override
    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";
    }

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

 

package Flyweight10_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++){
            System.out.print("第"+i+"个圆: ");
            int x = random.nextInt(colors.length);
            Shape shape = factory.getShap(colors[x]);
            shape.draw(random.nextInt(2022),random.nextInt(100));
        }
    }
}
//FlyweightFactory
class ShapeFactory{
    private Map<String ,Shape> map = new HashMap<>();

    public Shape getShap(String key){
        if(map.containsKey(key)){
            return map.get(key);
        }else {
            Shape shape = new Circle(key);
            map.put(key, shape);
            return shape;
        }
    }
}
//Flyweight
abstract class Shape{
    protected String color;

    public abstract void draw(int x,int y);
}
//ConcreteFlyweight
class Circle extends Shape{
    public Circle(String color){
        System.out.println("create circle color: "+ color);
        this.color = color;
    }

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

 

3.Command命令模式

 

示例代码:

package Command11;

/**
 * 命令模式:
 * 意图:将一个请求封装为对象,从而使得可以用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。
 * 适用于:
 *      抽象出待执行的动作以参数化某对象
 *      在不同时刻指定、排列和执行请求
 *      支持取消操作
 *      支持修改日志
 *      用构建在原语操作上的高层操作构造一个系统
 */
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();
    }
}
//Receiver
class Tv {
    public void OnAction(){
        System.out.println("开机...");
    }
    public void OffAction(){
        System.out.println("关机...");
    }
}

 

4.Observer观察者模式

 

示例代码:

package Observer12;

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

/**
 * 观察者模式:
 * 意图: 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新
 * 适用于:
 *      当一个对象的改变需要同时改变其他对象,而且不知道有多少个对象有待改变
 */
public class ObserverPattern {
    public static void main(String[] args) {
        Subject subjectA = new ConcreteSubject("目标A");
        Observer observerB = new ConcreteObserver("张三",subjectA);
        Observer observerC = new ConcreteObserver("李四",subjectA);
        Observer observerD = new ConcreteObserver("王五",subjectA);
//        System.out.println("目标A的状态改变后...");
        subjectA.setState("已更新...");
//        subjectA.Notify();
        subjectA.setState("停更了...");
    }
}
//目标接口
interface Subject{
    public void Attach(Observer observer);
    public void Detach(Observer observer);
    //状态改变后,通知所有观察者
    public void Notify();

    public void setState(String state);
    public String getState();
}
class ConcreteSubject implements Subject{
    private String name;
    private String state;
    private List<Observer> observerList;
    public ConcreteSubject(String name){
        this.name=name;
        state="未更新";
        observerList = new ArrayList<Observer>();
    }

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

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

    @Override
    public void Notify() {
        for (Observer observer: observerList) {
            observer.update();
        }
    }

    @Override
    public void setState(String state) {
        this.state=state;
        System.out.println(name+"的状态发生变化,变化后状态为: "+state);
        Notify();
    }

    @Override
    public String getState() {
        return this.state;
    }
}
//观察者接口
interface Observer{
    public void update();
}
class ConcreteObserver implements Observer{
    private String state;
    private String name;
    //指明目标
    private Subject subject;

    public ConcreteObserver(String name,Subject subject){
        this.state=subject.getState();
        this.name=name;
        this.subject = subject;
        subject.Attach(this);
    }

    @Override
    public void update() {
        System.out.println(name+"收到通知");
        state = subject.getState();
        System.out.println(name+"改变后的状态: "+state);
    }
}

 

posted on 2023-10-27 21:03  201812  阅读(22)  评论(0编辑  收藏  举报