首页 > 编程语言 >JAVA的设计模式都有那些

JAVA的设计模式都有那些

时间:2024-10-26 20:48:38浏览次数:3  
标签:implements JAVA void private class 那些 new 设计模式 public

        Java设计模式是为了解决软件开发中常见的问题而创建的一系列最佳实践。它们提供了一种在特定情境下解决问题的方法论,并且已经被广泛验证和应用。这些模式不是具体的代码,而是关于如何组织代码以达到某种目的的高层次描述。设计模式通常分为三大类:创建型模式、结构型模式和行为型模式。

一  创建型模式

这类模式主要处理对象的创建方式,目的是将系统与具体类解耦。

       1. 单例模式 (Singleton Pattern)

                 确保一个类只有一个实例,并提供一个全局访问点。例如,数据库连接池或日志记录器。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

       2. 工厂方法模式 (Factory Method Pattern)

                定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。

interface Product { void use(); }

class ConcreteProduct implements Product { public void use() {} }

abstract class Creator {
    public final Product create(String type) {
        Product product = factoryMethod(type);
        // 准备、初始化等
        return product;
    }
    protected abstract Product factoryMethod(String type);
}

class ConcreteCreator extends Creator {
    protected Product factoryMethod(String type) {
        if ("A".equals(type)) {
            return new ConcreteProduct();
        } else {
            throw new IllegalArgumentException("Invalid product type");
        }
    }
}

       3. 抽象工厂模式 (Abstract Factory Pattern)

                提供一个接口来创建一系列相关或相互依赖的对象,而无需指定它们的具体类。

interface AbstractFactory {
    ProductA createProductA();
    ProductB createProductB();
}

class ConcreteFactory1 implements AbstractFactory {
    public ProductA createProductA() { return new ConcreteProductA1(); }
    public ProductB createProductB() { return new ConcreteProductB1(); }
}

// 其他产品和工厂实现...

       4. 建造者模式 (Builder Pattern)

                将复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

class Product {
    // 复杂对象属性
}

interface Builder {
    void buildPartA();
    void buildPartB();
    Product getResult();
}

class ConcreteBuilder implements Builder {
    private Product product = new Product();

    public void buildPartA() { /* 构建部分A */ }
    public void buildPartB() { /* 构建部分B */ }
    public Product getResult() { return product; }
}

class Director {
    private Builder builder;

    public Director(Builder builder) { this.builder = builder; }

    public void construct() {
        builder.buildPartA();
        builder.buildPartB();
    }
}

       5. 原型模式 (Prototype Pattern)

                通过复制现有实例来创建新实例,而不是通过构造函数创建。

interface Prototype {
    Prototype clone();
}

class ConcretePrototype implements Prototype, Cloneable {
    @Override
    public Prototype clone() {
        try {
            return (ConcretePrototype) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}

二  结构型模式

         结构型模式关注于如何组合类和对象以形成更大的结构,同时保持结构的灵活性和高效性。

       1. 适配器模式 (Adapter Pattern)

                允许不兼容接口的对象能够一起工作。

interface Target {
    void request();
}

class Adaptee {
    void specificRequest() {}
}

class Adapter implements Target {
    private Adaptee adaptee;

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

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

       2. 桥接模式 (Bridge Pattern)

                将抽象部分与它的实现部分分离,使它们都可以独立地变化。

interface Implementor {
    void operationImpl();
}

class ConcreteImplementorA implements Implementor {
    public void operationImpl() { /* 实现细节 */ }
}

abstract class Abstraction {
    protected Implementor implementor;

    public void setImplementor(Implementor implementor) {
        this.implementor = implementor;
    }

    public abstract void operation();
}

class RefinedAbstraction extends Abstraction {
    public void operation() {
        implementor.operationImpl();
    }
}

       3. 装饰器模式 (Decorator Pattern)

                动态地给一个对象添加一些额外的职责。

interface Component {
    void operation();
}

class ConcreteComponent implements Component {
    public void operation() { /* 基本功能 */ }
}

abstract class Decorator implements Component {
    protected Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    public void operation() {
        component.operation();
    }
}

class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) { super(component); }

    public void addedBehavior() { /* 额外的行为 */ }

    public void operation() {
        super.operation();
        addedBehavior();
    }
}

       4. 外观模式 (Facade Pattern)

                提供了一个统一的接口,用来访问子系统中的一群接口。

class Subsystem1 { public void operation1() {} }
class Subsystem2 { public void operation2() {} }
class Subsystem3 { public void operation3() {} }

class Facade {
    private Subsystem1 subsystem1;
    private Subsystem2 subsystem2;
    private Subsystem3 subsystem3;

    public Facade() {
        subsystem1 = new Subsystem1();
        subsystem2 = new Subsystem2();
        subsystem3 = new Subsystem3();
    }

    public void operation() {
        subsystem1.operation1();
        subsystem2.operation2();
        subsystem3.operation3();
    }
}

       5. 享元模式 (Flyweight Pattern)

                用于减少创建对象的数量,以减少内存占用并提高性能。

interface Flyweight {
    void operation(int extrinsicState);
}

class ConcreteFlyweight implements Flyweight {
    private int intrinsicState;

    public ConcreteFlyweight(int intrinsicState) {
        this.intrinsicState = intrinsicState;
    }

    public void operation(int extrinsicState) {
        System.out.println("Intrinsic State: " + intrinsicState + ", Extrinsic State: " + extrinsicState);
    }
}

class FlyweightFactory {
    private Map<Integer, ConcreteFlyweight> flyweights = new HashMap<>();

    public Flyweight getFlyweight(int key) {
        if (!flyweights.containsKey(key)) {
            flyweights.put(key, new ConcreteFlyweight(key));
        }
        return flyweights.get(key);
    }
}

       6. 代理模式 (Proxy Pattern)

                为其他对象提供一种代理以控制对这个对象的访问。

interface Subject {
    void request();
}

class RealSubject implements Subject {
    public void request() { /* 实际操作 */ }
}

class Proxy implements Subject {
    private RealSubject realSubject;

    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        preRequest();
        realSubject.request();
        postRequest();
    }

    private void preRequest() { /* 在请求前执行的操作 */ }
    private void postRequest() { /* 在请求后执行的操作 */ }
}

       7. 组合模式 (Composite Pattern)

                允许你将对象组合成树形结构来表示“部分-整体”的层次结构。

interface Component {
    void add(Component c);
    void remove(Component c);
    void display(int depth);
}

class Leaf implements Component {
    public void add(Component c) { throw new UnsupportedOperationException(); }
    public void remove(Component c) { throw new UnsupportedOperationException(); }
    public void display(int depth) { for (int i = 0; i < depth; i++) { System.out.print("-"); } System.out.println("Leaf"); }
}

class Composite implements Component {
    private List<Component> children = new ArrayList<>();

    public void add(Component c) { children.add(c); }
    public void remove(Component c) { children.remove(c); }
    public void display(int depth) {
        for (int i = 0; i < depth; i++) { System.out.print("-"); }
        System.out.println("+ Composite");
        for (Component child : children) {
            child.display(depth + 1);
        }
    }
}

三  行为型模式

         行为型模式涉及对象之间的通信和协作,以及分配责任和算法的方式。

       1. 策略模式 (Strategy Pattern)

                定义了一系列可互换的算法,并将每个算法封装起来,使得算法的变化独立于使用算法的客户。

interface Strategy {
    int doOperation(int num1, int num2);
}

class OperationAdd implements Strategy {
    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);
    }
}

       2. 观察者模式 (Observer Pattern)

                当一个对象的状态改变时,所有依赖它的对象都会收到通知并自动更新。

interface Observer {
    void update(String message);
}

interface Subject {
    void attach(Observer observer);
    void detach(Observer observer);
    void notifyObservers(String message);
}

class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();

    public void attach(Observer observer) { observers.add(observer); }
    public void detach(Observer observer) { observers.remove(observer); }
    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}

class ConcreteObserver implements Observer {
    public void update(String message) { System.out.println("Received: " + message); }
}

       3. 命令模式 (Command Pattern)

                将请求封装为一个对象,从而使你可以用不同的请求对客户进行参数化。

interface Command {
    void execute();
}

class ConcreteCommand implements Command {
    private Receiver receiver;

    public ConcreteCommand(Receiver receiver) { this.receiver = receiver; }

    public void execute() { receiver.action(); }
}

class Receiver {
    public void action() { /* 执行实际动作 */ }
}

class Invoker {
    private Command command;

    public void setCommand(Command command) { this.command = command; }

    public void executeCommand() { command.execute(); }
}

       4. 状态模式 (State Pattern)

                允许一个对象在其内部状态改变时改变其行为。

interface State {
    void handle(Context context);
}

class ConcreteStateA implements State {
    public void handle(Context context) {
        context.setState(new ConcreteStateB());
        System.out.println("Switch to State B");
    }
}

class ConcreteStateB implements State {
    public void handle(Context context) {
        context.setState(new ConcreteStateA());
        System.out.println("Switch to State A");
    }
}

class Context {
    private State state;

    public Context(State state) { this.state = state; }

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

    public void request() { state.handle(this); }
}

       5. 模板方法模式 (Template Method Pattern)

                定义了一个算法的骨架,而将一些步骤延迟到子类中。

abstract class AbstractClass {
    public final void templateMethod() {
        primitiveOperation1();
        primitiveOperation2();
    }

    protected abstract void primitiveOperation1();
    protected abstract void primitiveOperation2();
}

class ConcreteClass extends AbstractClass {
    protected void primitiveOperation1() { /* 实现操作1 */ }
    protected void primitiveOperation2() { /* 实现操作2 */ }
}

       6. 中介者模式 (Mediator Pattern)

                 用一个中介对象来封装一系列的对象交互。

interface Mediator {
    void notify(Object sender, String ev);
}

class ConcreteMediator implements Mediator {
    private Component1 component1;
    private Component2 component2;

    public ConcreteMediator(Component1 c1, Component2 c2) {
        this.component1 = c1;
        this.component2 = c2;
    }

    public void notify(Object sender, String ev) {
        if (ev.equals("A")) {
            component2.doC();
        } else if (ev.equals("D")) {
            component1.doB();
        }
    }
}

class Component1 {
    private Mediator mediator;

    public Component1(Mediator mediator) { this.mediator = mediator; }

    public void doA() { mediator.notify(this, "A"); }
    public void doB() { System.out.println("Doing B"); }
}

class Component2 {
    private Mediator mediator;

    public Component2(Mediator mediator) { this.mediator = mediator; }

    public void doC() { System.out.println("Doing C"); }
    public void doD() { mediator.notify(this, "D"); }
}

       7. 迭代器模式 (Iterator Pattern)

                提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。

interface Iterator {
    boolean hasNext();
    Object next();
}

interface Container {
    Iterator getIterator();
}

class NameRepository implements Container {
    public String names[] = {"Robert", "John", "Julie", "Lora"};

    public Iterator getIterator() {
        return new NameIterator();
    }

    private class NameIterator implements Iterator {
        int index;

        public boolean hasNext() {
            if (index < names.length) {
                return true;
            }
            return false;
        }

        public Object next() {
            if (this.hasNext()) {
                return names[index++];
            }
            return null;
        }
    }
}

       8. 访问者模式 (Visitor Pattern)

                在不改变数据结构的前提下,增加作用于一组对象元素的新功能。

interface Element {
    void accept(Visitor v);
}

interface Visitor {
    void visitConcreteElementA(ConcreteElementA a);
    void visitConcreteElementB(ConcreteElementB b);
}

class ConcreteElementA implements Element {
    public void accept(Visitor v) { v.visitConcreteElementA(this); }
    public void operationA() { /* 操作A */ }
}

class ConcreteElementB implements Element {
    public void accept(Visitor v) { v.visitConcreteElementB(this); }
    public void operationB() { /* 操作B */ }
}

class ConcreteVisitor1 implements Visitor {
    public void visitConcreteElementA(ConcreteElementA a) { a.operationA(); }
    public void visitConcreteElementB(ConcreteElementB b) { b.operationB(); }
}

class ConcreteVisitor2 implements Visitor {
    public void visitConcreteElementA(ConcreteElementA a) { a.operationA(); }
    public void visitConcreteElementB(ConcreteElementB b) { b.operationB(); }
}

        以上只是每种设计模式的一个简单示例。在实际开发过程中,你需要根据具体的需求和场景选择合适的设计模式。设计模式不仅帮助解决常见问题,还促进了代码复用、增强了程序的可维护性和扩展性。理解并熟练运用这些模式,可以帮助开发者编写出更加优雅和高效的代码。

标签:implements,JAVA,void,private,class,那些,new,设计模式,public
From: https://blog.csdn.net/m0_50742275/article/details/143259135

相关文章

  • Java中TreeSet的使用
    TreeSet的使用文章目录TreeSet的使用判断数据是否相同的标准添加String类型对象添加自定义类型对象定制排序底层数据结构:红黑树添加元素后的特点:可以按照添加的元素的指定的属性的大小顺序进行遍历添加元素的要求:添加到TreeSet的元素必须是同一个类型的对......
  • 基于Java+SpringBoot+Mysql实现的古诗词平台功能设计与实现一
    一、前言介绍:1.1项目摘要随着信息技术的迅猛发展和数字化时代的到来,传统文化与现代科技的融合已成为一种趋势。古诗词作为中华民族的文化瑰宝,具有深厚的历史底蕴和独特的艺术魅力。然而,在现代社会中,由于生活节奏的加快和信息获取方式的多样化,古诗词的传播和阅读面临着一定的挑......
  • 高级java每日一道面试题-2024年10月24日-JVM篇-说一下JVM有哪些垃圾回收器?
    如果有遗漏,评论区告诉我进行补充面试官:说一下JVM有哪些垃圾回收器?我回答:1.Serial收集器特点:Serial收集器是最古老、最稳定的收集器,它使用单个线程进行垃圾收集工作。在进行垃圾回收时,它会暂停所有用户线程,即StopTheWorld(STW)。单线程工作,适合单核CPU。在年......
  • 高级java每日一道面试题-2024年10月23日-JVM篇-说一下JVM有哪些垃圾回收算法?
    如果有遗漏,评论区告诉我进行补充面试官:说一下JVM有哪些垃圾回收算法?我回答:在Java虚拟机(JVM)中,垃圾回收(GarbageCollection,GC)是一项非常重要的功能,用于自动管理应用程序的内存。JVM采用多种垃圾回收算法来决定何时以及如何回收不再使用的对象所占用的内......
  • JavaScript CSS Vue3 实现一个简单的Loading
    之前项目用到的,后来换其他效果了。放博客里保存一下。效果视频转GIF之后不太流畅……代码<scriptsetuplang="ts">import{onBeforeUnmount,onMounted,ref}from"vue";import{clamp}from"../scripts/Utils";constmaskDiv=ref<HTMLDivElement>(null)co......
  • 最新毕设-SpringBoot-健康体检系统-12791(免费领项目)可做计算机毕业设计JAVA、PHP、爬
    springboot健康体检系统摘要在如今IT技术快速发展和Internet广泛应用的时代,电子和网络技术给人们生活带来了便利,同时也会直接或间接损害人们的健康。所以,本次的毕业设计创作的意义就是通过信息化的统一管理,给用户尽心健康体检预约提供了方便。本设计主要实现集人性化、高效......
  • (2024最新毕设合集)基于Django的房价分析平台-65434|可做计算机毕业设计JAVA、PHP、爬虫
    摘要本论文主要论述了如何基于Django框架开发一个房价分析平台,本系统将严格按照软件开发流程进行各个阶段的工作,通过爬虫技术对贵州省的房价数据进行爬取,面向对象编程思想进行项目开发。在引言中,作者将论述房价分析平台的当前背景以及系统开发的目的,后续章节将严格按照软件......
  • Java 面试题【MySQL 篇 一】
    MySQL中的数据排序是怎么实现的?参考链接:MySQL中的数据排序是怎么实现的?-MySQL面试题-面试鸭-程序员求职面试刷题神器排序过程中,如果排序字段命中索引,则利用索引排序。反之,使用文件排序。文件排序中,如果数据量少则在内存中排序,具体是使用单路排序或者双路排序。......
  • java 为什么有private关键字_2
    在讨论编程语言设计时,Java语言中的`private`关键字扮演着至关重要的角色。私有访问修饰符`private`的主要目的是封装、数据隐藏。通过限制对类成员的访问,它确保了对象的内部状态不能被外部代码随意修改,从而保护了对象的完整性和一致性。这种封装机制是面向对象编程(OOP)的核心原则......
  • 液体(java)
    题目描述:现在有n个物品,每个物品都是液体,液体存在重量和价值,现在要求你只能从如下提供的液体中总共取走10升液体,每种液体每次可以不拿,全拿,或拿一部分,问取走的10升液体的最高价值是多少。请用程序来完成。名称重量(升)总价值水424牛奶8160五粮液24000可乐6108茅......