原型,模板,策略,适配器模式

news/2024/7/23 18:39:48 标签: 适配器模式, 设计模式, 原型模式

原型模式

原型模式(创建型模式),核心思想就是:基于一个已有的对象复制一个对象出来,通过复制来减少对象的直接创建的成本。
总结一下,原型模式的两种方法,浅拷贝只会复制对象里面的基本数据类型和引用对象的内存地址,不会递归地复制引用对象,以及引用对象的引用对象。而深拷贝就是会完全拷贝一个新的对象出来。所以,深拷贝的操作会比浅拷贝更加耗时,性能更差一点。同时浅拷贝的代码写起来也比深拷贝的代码写起来更简单一点。如果咱们拷贝的对象是不可变的,也就是说我这个对象只会查看,不会增删改,那么,直接用浅拷贝就好了,如果拷贝的对象存在增删改的情况,那么就需要使用深拷贝了。总而言之,就是要深浅得当,根据项目实际情况而定。
代码举例

// 原型接口
interface Shape extends Cloneable {
    void draw();
    Shape clone();
}

// 具体原型类 - 圆形
class Circle implements Shape {
    private String color;

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

    @Override
    public void draw() {
        System.out.println("Drawing a circle with color: " + color);
    }

    @Override
    public Shape clone() {
        return new Circle(color);
    }
}

// 具体原型类 - 正方形
class Square implements Shape {
    private String color;

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

    @Override
    public void draw() {
        System.out.println("Drawing a square with color: " + color);
    }

    @Override
    public Shape clone() {
        return new Square(color);
    }
}

// 原型管理器
class ShapeCache {
    private static Map<String, Shape> shapeMap = new HashMap<>();

    public static Shape getShape(String type) {
        Shape cachedShape = shapeMap.get(type);
        return (Shape) cachedShape.clone();
    }

    public static void loadCache() {
        Circle circle = new Circle("red");
        shapeMap.put("circle", circle);

        Square square = new Square("blue");
        shapeMap.put("square", square);
    }
}

// 示例使用
public class PrototypePatternExample {
    public static void main(String[] args) {
        ShapeCache.loadCache();

        Shape clonedShape1 = ShapeCache.getShape("circle");
        clonedShape1.draw();  // 输出: Drawing a circle with color: red

        Shape clonedShape2 = ShapeCache.getShape("square");
        clonedShape2.draw();  // 输出: Drawing a square with color: blue
    }
}

模板模式

模板方法模式也非常简单,但是,他却是比较重要的,在很多开源框架里面都用到了这个模式,并且,我们在做项目的时候,也会经常用到这个模式。这个模板方法模式,简单来说就是一句话:在父类中定义业务处理流程的框架,到子类中去做具体的实现。

代码举例

// 抽象模板类
abstract class Game {
    abstract void initialize();
    abstract void startPlay();
    abstract void endPlay();

    // 模板方法,定义算法框架
    public final void play() {
        initialize();
        startPlay();
        endPlay();
    }
}

// 具体模板类 - 足球游戏
class FootballGame extends Game {
    @Override
    void initialize() {
        System.out.println("Football Game Initialized! Start playing.");
    }

    @Override
    void startPlay() {
        System.out.println("Playing football...");
    }

    @Override
    void endPlay() {
        System.out.println("Football Game Finished!");
    }
}

// 具体模板类 - 篮球游戏
class BasketballGame extends Game {
    @Override
    void initialize() {
        System.out.println("Basketball Game Initialized! Start playing.");
    }

    @Override
    void startPlay() {
        System.out.println("Playing basketball...");
    }

    @Override
    void endPlay() {
        System.out.println("Basketball Game Finished!");
    }
}

// 示例使用
public class TemplatePatternExample {
    public static void main(String[] args) {
        Game footballGame = new FootballGame();
        footballGame.play();
        // 输出:
        // Football Game Initialized! Start playing.
        // Playing football...
        // Football Game Finished!

        System.out.println();

        Game basketballGame = new BasketballGame();
        basketballGame.play();
        // 输出:
        // Basketball Game Initialized! Start playing.
        // Playing basketball...
        // Basketball Game Finished!
    }
}

策略模式

接着我们来看一下策略模式,策略模式呢也是非常简单,他就是定义一个主要的接口,然后很多个类去实现这个接口,比如说我们定义一个文件上传的接口,然后阿里云的上传类去实现它,腾讯云的上传类也去实现它,这样因为都是实现的同一个接口,所以上传类之间是可以在代码中互相替换的。

代码举例

// 策略接口
interface Strategy {
    int doOperation(int num1, int num2);
}

// 具体策略类 - 加法
class AddStrategy implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

// 具体策略类 - 减法
class SubtractStrategy implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

// 上下文类
class Context {
    private Strategy strategy;

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

    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }
}

// 示例使用
public class StrategyPatternExample {
    public static void main(String[] args) {
        Context context = new Context(new AddStrategy());
        int result1 = context.executeStrategy(10, 5);
        System.out.println("10 + 5 = " + result1);  // 输出: 10 + 5 = 15

        context = new Context(new SubtractStrategy());
        int result2 = context.executeStrategy(10, 5);
        System.out.println("10 - 5 = " + result2);  // 输出: 10 - 5 = 5
    }
}

委派模式

委派模式(Delegate Pattern)又叫委托模式,是一种面向对象的设计模式,基本作用就是负责任务的调用和分配;是一种特殊的静态代理,可以理解为全权代理(代理模式注重过程,而委派模式注重结果),委派模式属于行为型模式,不属于GOF23种设计模式

代码举例

// 委派接口
interface Printer {
    void print();
}

// 具体委派类 - 打印机A
class PrinterA implements Printer {
    @Override
    public void print() {
        System.out.println("Printer A is printing.");
    }
}

// 具体委派类 - 打印机B
class PrinterB implements Printer {
    @Override
    public void print() {
        System.out.println("Printer B is printing.");
    }
}

// 委派类
class PrinterManager {
    private Printer printer;

    public void setPrinter(Printer printer) {
        this.printer = printer;
    }

    public void print() {
        printer.print();
    }
}

// 示例使用
public class DelegatePatternExample {
    public static void main(String[] args) {
        PrinterManager printerManager = new PrinterManager();

        // 使用打印机A
        PrinterA printerA = new PrinterA();
        printerManager.setPrinter(printerA);
        printerManager.print();  // 输出: Printer A is printing.

        System.out.println();

        // 使用打印机B
        PrinterB printerB = new PrinterB();
        printerManager.setPrinter(printerB);
        printerManager.print();  // 输出: Printer B is printing.
    }
}

适配器模式

适配器模式也比较简单,核心思想就是是:将一个类的接口转换成客户希望的另一个接口,讲白了就是通过适配器可以将原本不匹配、不兼容的接口或类结合起来;

代码举例

// 目标接口
interface Target {
    void request();
}

// 适配者类
class Adaptee {
    public void specificRequest() {
        System.out.println("Specific request from Adaptee.");
    }
}

// 适配器类
class Adapter implements Target {
    private Adaptee adaptee;

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

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

// 示例使用
public class AdapterPatternExample {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target adapter = new Adapter(adaptee);

        adapter.request();  // 输出: Specific request from Adaptee.
    }
}


http://www.niftyadmin.cn/n/5439360.html

相关文章

leetcode-hot100-图论

200. 岛屿数量 给你一个由 1&#xff08;陆地&#xff09;和 0&#xff08;水&#xff09;组成的的二维网格&#xff0c;请你计算网格中岛屿的数量。 岛屿总是被水包围&#xff0c;并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。 此外&#xff0c;你可以假…

OpenJudge - 13:大整数的因子

总时间限制: 1000ms 内存限制: 65536kB 描述 已知正整数k满足2<k<9&#xff0c;现给出长度最大为30位的十进制非负整数c&#xff0c;求所有能整除c的k。 输入 一个非负整数c&#xff0c;c的位数<30。 输出 若存在满足 c%k 0 的k&#xff0c;从小到大输出所有这样的…

MySQL事务隔离级别及MVCC详解

MySQL的事务隔离级别及特性如下&#xff1a; SERIALIZABLE&#xff08;串行化&#xff09;&#xff1a;无问题&#xff0c;性能差&#xff1b; REPEATABLE-READ&#xff08;可重复读&#xff09;&#xff1a;幻读&#xff0c;默认隔离级别&#xff1b; READ-COMMITTED&#xf…

Springboot笔记-03

1.properties配置文件 #配制oerson的值 person.lastname张三 person.age12 person.birth2017/12/12 person.bossfalse person.dog.namedag person.dog.age15 person.maps.k1v1 person.maps.k212 person.listsa,b,c运行结果乱码 因为idea默认是utf-8编码而properties是ascall编…

MySQL的锁的类型

乐观锁与悲观锁&#xff1a; 乐观锁&#xff08;Optimistic Lock&#xff09;通常不直接锁定数据&#xff0c;而是在更新时检查数据是否已被其他事务修改。如果发现冲突&#xff0c;则放弃本次操作或重试。 悲观锁&#xff08;Pessimistic Lock&#xff09;则是在操作数据之前…

【Godot4.2】2D导航02 - AstarGrid2D及其使用方法

概述 AstarGrid2D是Godot4.0新增的A*寻路辅助类型。可以看做是Astar2D的加强版。它允许你通过设置其size和cell_size属性来创建一个虚拟的网格。 并使用set_point_solid()这样的方法来在指定位置创建障碍物。 AstarGrid2D的好处是你不再需要手动的添加点以及点与点之间的连接…

C语言 指针练习

一、 a、b是两个浮点型变量&#xff0c;给a、b赋值&#xff0c;建立两个指针分别指向a的地址和b的地址&#xff0c;输出两个指针的值。 #include<stdio.h> int main() {float a,b,*p1,*p2;a10.2;b2.3;p1&a;p2&b;printf("a%f,b%f\n",a,b);printf("…

Infineon_TC264智能车代码初探及C语言深度学习(二)

本篇文章记录我在智能车竞赛中&#xff0c;对 Infineon_TC264 这款芯片的底层库函数的学习分析。通过深入地对其库函数进行分析&#xff0c;C语言深入的知识得以再次在编程中呈现和运用。故觉得很有必要在此进行记录分享一下。 目录 ​编辑 一、代码段分析 NO.1 指向结构体…