Java七种常用设计模式

这篇具有很好参考价值的文章主要介绍了Java七种常用设计模式。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、单例模式(Singleton Pattern)

单例模式是(Singleton Pattern)Java中最常用的设计模式之一,它保证一个类仅有一个实例,并提供一个全局访问点。

实现单例模式的核心是将类的构造方法私有化,以防止外部直接通过构造函数创建实例。同时,类内部需要提供一个静态方法或变量来获取该类的唯一实例。

以下是一个简单的单例模式实现:

public class Singleton {
    private static Singleton instance = null;

    // 私有构造方法
    private Singleton() {
    }

    // 静态方法,获取唯一实例
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

2、工厂模式(Factory Pattern)

工厂模式(Factory Pattern)是Java中常用的一种创建型设计模式,它提供了一种将对象创建的过程封装起来的方法,可以根据不同的参数来创建不同类型的对象。

工厂模式有三种常用的实现方式:简单工厂模式、工厂方法模式和抽象工厂模式。以简单工厂模式为例,实现过程如下:

  1. 定义抽象产品类:
public abstract class Product {
    public abstract void use();
}
  1. 定义具体产品类:
public class ProductA extends Product {
    @Override
    public void use() {
        System.out.println("使用产品A");
    }
}

public class ProductB extends Product {
    @Override
    public void use() {
        System.out.println("使用产品B");
    }
}
  1. 定义工厂类:
public class Factory {
    public static Product createProduct(String type) {
        if ("A".equals(type)) {
            return new ProductA();
        } else if ("B".equals(type)) {
            return new ProductB();
        } else {
            throw new IllegalArgumentException("无效的产品类型");
        }
    }
}
  1. 调用工厂类创建产品:
Product productA = Factory.createProduct("A");
productA.use(); // 输出:使用产品A

Product productB = Factory.createProduct("B");
productB.use(); // 输出:使用产品B

在上述实现中,AbstractProduct是一个抽象产品类,定义了产品的基本属性和方法。ProductAProductB是具体的产品类,实现了抽象产品类中定义的方法。

Factory是一个工厂类,根据不同的参数创建不同类型的产品对象。Factory中的方法是静态的,无需先创建工厂对象再调用方法。

通过使用工厂模式,可以有效地封装对象的创建过程,实现了高内聚、低耦合的设计思想,也使得代码更加易于维护和扩展。

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

抽象工厂模式(Abstract Factory Pattern)是Java中常用的一种创建型设计模式,它提供了一种创建一系列相关或相互依赖的对象接口,而无需指定它们具体的类。

抽象工厂模式和工厂方法模式类似,不同之处在于抽象工厂模式中工厂类不单独生产一种产品,而是生产一系列相关的产品。

以下是一个简单的抽象工厂模式实现:

  1. 定义抽象产品类:
public interface AbstractProductA {
    void use();
}

public interface AbstractProductB {
    void consume();
}
  1. 定义具体产品类:
public class ProductA1 implements AbstractProductA {
    @Override
    public void use() {
        System.out.println("使用ProductA1");
    }
}

public class ProductA2 implements AbstractProductA {
    @Override
    public void use() {
        System.out.println("使用ProductA2");
    }
}

public class ProductB1 implements AbstractProductB {
    @Override
    public void consume() {
        System.out.println("消费ProductB1");
    }
}

public class ProductB2 implements AbstractProductB {
    @Override
    public void consume() {
        System.out.println("消费ProductB2");
    }
}
  1. 定义抽象工厂类:
public interface AbstractFactory {
    AbstractProductA createProductA();

    AbstractProductB createProductB();
}
  1. 定义具体工厂类:
public class Factory1 implements AbstractFactory {
    @Override
    public AbstractProductA createProductA() {
        return new ProductA1();
    }

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

public class Factory2 implements AbstractFactory {
    @Override
    public AbstractProductA createProductA() {
        return new ProductA2();
    }

    @Override
    public AbstractProductB createProductB() {
        return new ProductB2();
    }
}
  1. 调用抽象工厂生成产品:
AbstractFactory factory1 = new Factory1();
AbstractProductA productA1 = factory1.createProductA();
AbstractProductB productB1 = factory1.createProductB();
productA1.use(); // 输出:使用ProductA1
productB1.consume(); // 输出:消费ProductB1

AbstractFactory factory2 = new Factory2();
AbstractProductA productA2 = factory2.createProductA();
AbstractProductB productB2 = factory2.createProductB();
productA2.use(); // 输出:使用ProductA2
productB2.consume(); // 输出:消费ProductB2

以上是一个简单的抽象工厂模式实现。其中,抽象工厂类AbstractFactory定义抽象方法createProductA()createProductB(),用于创建AbstractProductAAbstractProductB类型的对象。

具体工厂类Factory1Factory2分别实现AbstractFactory接口,并实现了接口中定义的两个抽象方法,分别生产ProductA1ProductB1ProductA2ProductB2类型的对象。

通过使用抽象工厂模式,可以更加灵活地生成一系列相关的产品。它能够隔离类的实例化过程,客户端使用抽象工厂创建的对象是一系列相关的产品,无需关心具体的实现。

4、建造者模式(Builder Pattern)

建造者模式(Builder Pattern)是Java中常用的一种创建型设计模式,它将一个复杂的对象的构建过程和表示分离开来,使得同样的构建过程可以创建不同的表示。

建造者模式主要由4部分组成:抽象建造者、具体建造者、指挥者和产品。其中,抽象建造者和具体建造者用于定义和实现产品的创建过程,指挥者协调建造者来构建产品,而产品则是最终构建出的对象。

以下是一个简单的建造者模式实现:

  1. 定义产品类:
public class Product {
    private String partA;
    private String partB;
    private String partC;

    public String getPartA() {
        return partA;
    }

    public void setPartA(String partA) {
        this.partA = partA;
    }

    public String getPartB() {
        return partB;
    }

    public void setPartB(String partB) {
        this.partB = partB;
    }

    public String getPartC() {
        return partC;
    }

    public void setPartC(String partC) {
        this.partC = partC;
    }

    @Override
    public String toString() {
        return "Product{" +
                "partA='" + partA + '\'' +
                ", partB='" + partB + '\'' +
                ", partC='" + partC + '\'' +
                '}';
    }
}
  1. 定义抽象建造者类:
public abstract class Builder {
    public abstract void buildPartA();

    public abstract void buildPartB();

    public abstract void buildPartC();

    public abstract Product getResult();
}
  1. 定义具体建造者类:
public class ConcreteBuilder extends Builder {
    private Product product = new Product();

    @Override
    public void buildPartA() {
        product.setPartA("PartA");
    }

    @Override
    public void buildPartB() {
        product.setPartB("PartB");
    }

    @Override
    public void buildPartC() {
        product.setPartC("PartC");
    }

    @Override
    public Product getResult() {
        return product;
    }
}
  1. 定义指挥者类:
public class Director {
    private Builder builder;

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

    public void construct() {
        builder.buildPartA();
        builder.buildPartB();
        builder.buildPartC();
    }
}
  1. 创建产品:
Builder builder = new ConcreteBuilder();
Director director = new Director(builder);
director.construct();
Product product = builder.getResult();
System.out.println(product);

在上述实现中,Product是一个产品类,该类具有多个属性,通过访问器和修改器可以进行属性的获取和设置。

Builder是一个抽象建造者类,定义了产品的构建方法。具体建造者类ConcreteBuilder实现了建造者接口中的所有方法,实现了对产品的创建过程。Director是一个指挥者类,负责控制整个建造过程的进行。

最后,通过建造者模式创建产品。指挥者将具体的建造过程委托给建造者完成,而建造者根据指挥者提供的具体信息来创建不同的产品。通过使用建造者模式,可以灵活地构建具有复杂结构的产品。

5、策略模式(Strategy Pattern)

策略模式(Strategy Pattern)是Java中常用的一种行为型设计模式,它定义了一系列算法,将每个算法封装起来,并且使它们可以互换,让算法独立于使用它的客户端而变化。

策略模式主要由三部分组成:策略接口、具体策略类和上下文类。策略接口定义了算法的统一接口,具体策略类实现了策略接口中定义的算法,而上下文类持有一个策略接口的引用,负责调用具体策略类中的算法。

以下是一个简单的策略模式实现:

  1. 定义策略接口:
public interface Strategy {
    void execute();
}
  1. 定义具体策略类:
public class StrategyA implements Strategy {
    @Override
    public void execute() {
        System.out.println("执行策略A");
    }
}

public class StrategyB implements Strategy {
    @Override
    public void execute() {
        System.out.println("执行策略B");
    }
}
  1. 定义上下文类:
public class Context {
    private Strategy strategy;

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

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public void doStrategy() {
        strategy.execute();
    }
}
  1. 使用策略模式:
Strategy strategyA = new StrategyA();
Context context = new Context(strategyA);
context.doStrategy(); // 输出:执行策略A

Strategy strategyB = new StrategyB();
context.setStrategy(strategyB);
context.doStrategy(); // 输出:执行策略B

在上述实现中,Strategy是一个抽象策略接口,定义了算法的统一接口。具体策略类StrategyAStrategyB实现了策略接口中的算法,为策略模式提供了具体的算法实现。

Context是一个上下文类,持有一个策略接口的引用,用于调用具体策略类中的算法。通过setStrategy()方法可以动态地改变策略,达到不同的行为。

6、装饰器模式(Decorator Pattern)

装饰器模式(Decorator Pattern)是一种结构型设计模式,用于动态地向一个对象添加一些额外的行为而不需要修改原来的类。

在该模式中,定义了一个装饰器类和一个组件类,被装饰对象是指该组件类及其子类的实例对象,装饰器类和被装饰对象具有相同的父类,即装饰器类和被装饰对象都是通过实现相同的接口或继承相同的抽象类来实现。

在实现时,装饰器类包含一个被装饰对象的成员变量,并维护一个指向被装饰对象的引用,在装饰器类中调用被装饰对象的方法时,还可以添加一些新的功能。

以下是简单的装饰器模式示例代码:

// 抽象组件
interface Component {
    void operation();
}
 
// 具体组件
class ConcreteComponent implements Component {
    public void operation() {
        System.out.println("基础操作");
    }
}

// 抽象装饰器
class Decorator implements Component {
    protected Component component;
 
    public Decorator(Component component) {
        this.component = component;
    }
 
    public void operation() {
        component.operation();
    }
}
 
// 具体装饰器
class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }
 
    public void operation() {
        super.operation();
        addedBehavior();
    }
 
    public void addedBehavior() {
        System.out.println("添加额外的行为");
    }
}

在上面的代码中,Component是被装饰对象的抽象接口,ConcreteComponent是具体的被装饰对象。在Decorator中,传入被装饰对象进行初始化,并重写operation()方法。而ConcreteDecorator是具体的装饰器,它继承自Decorator并扩展了被装饰对象的行为。

以下是测试装饰器的示例代码:

Component component = new ConcreteComponent(); // 创建被装饰对象
component.operation(); // 调用基础操作
 
Decorator decorator = new ConcreteDecorator(component); // 使用被装饰对象进行初始化
decorator.operation(); // 调用装饰器的操作方法,同时也会执行被装饰对象的操作方法和新添加的行为

在运行时,我们可以看到以下输出:

基础操作
基础操作
添加额外的行为

这表明操作被成功地传递到了被装饰者对象,并且具体的装饰器添加了额外的行为。

7、适配器模式(Adapter Pattern)

适配器模式(Adapter Pattern)是一种结构型设计模式,用于将一个已有类的接口转换成需要的接口形式。

适配器模式目的是让原本接口不兼容的类可以合作无间。在适配器模式中,适配器让一个类的接口与另一个类的接口相适应。

适配器的实现方法有两种:对象适配器和类适配器。

  • 对象适配器:适配器持有原始对象的引用,从而将其自己的接口与原始对象的接口“结合”在一起。
  • 类适配器:适配器通过多重继承实现将一个类的接口转换成另一个类所期望的接口形式。

以下是简单的适配器模式示例代码:

  • 对象适配器:

    // 原始接口
    interface Shape {
        void draw();
    }
    
    // 原始类
    class Rectangle implements Shape {
        public void draw() {
            System.out.println("Rectangle draw()");
        }
    }
    
    // 适配器类
    class ObjectAdapter implements Shape {
        private Rectangle rectangle;
    
        public ObjectAdapter(Rectangle rectangle) {
            this.rectangle = rectangle;
        }
    
        public void draw() {
            rectangle.draw();
        }
    }
    
    // 测试代码
    public class ObjectAdapterTest {
        public static void main(String[] args) {
            Rectangle rectangle = new Rectangle();
            Shape shape = new ObjectAdapter(rectangle);
            shape.draw();
        }
    }
    
  • 类适配器:

    // 原始类
    class Rectangle {
        void draw() {
            System.out.println("Rectangle draw()");
        }
    }
    
    // 目标接口
    interface Shape {
        void draw();
    }
    
    // 适配器类
    class ClassAdapter extends Rectangle implements Shape {
        public void draw() {
            super.draw();
        }
    }
    
    // 测试代码
    public class ClassAdapterTest {
        public static void main(String[] args) {
            Shape shape = new ClassAdapter();
            shape.draw();
        }
    }
    

在上面的代码中,我们有一个原始对象 Rectangle,它实现了 Shape 接口。在对象适配器模式中,我们创建了一个适配器 ObjectAdapter,以将该原始对象转换为 Shape 接口。在类适配器模式中,我们通过多重继承,将 Rectangle 类转换为 Shape 接口。在测试代码中,我们可以看到适配器的使用,将适配器对象传入客户端代码,并调用相应的方法。

总体来说,适配器模式是一种有效的设计模式,可以帮助我们处理接口不兼容的问题,从而使得不同的类可以相互协作完成任务。

8、观察者模式(Observer Pattern)

观察者模式(Observer Pattern)是一种行为型设计模式,也叫发布-订阅模式,它定义了对象之间一对多的依赖关系,使得当一个对象状态改变时,所有依赖它的对象都能收到通知并自动更新。

观察者模式中,有两种类型的对象:观察者和主题(或称为被观察者)。观察者将自己注册到主题,以便在主题的状态改变时接收通知。主题会维护一组观察者,并在自身状态改变时通知它们。主题通过调用观察者的统一接口来通知它们状态的变化。

以下是简单的观察者模式示例代码:

// 观察者接口
interface Observer {
    void update(String message);
}
 
// 具体观察者1
class ConcreteObserver1 implements Observer {
    @Override
    public void update(String message) {
        System.out.println("ConcreteObserver1:" + message);
    }
}
 
// 具体观察者2
class ConcreteObserver2 implements Observer {
    @Override
    public void update(String message) {
        System.out.println("ConcreteObserver2:" + message);
    }
}
 
// 主题接口
interface Subject {
    void registerObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObserver(String message);
}
 
// 具体主题
class ConcreteSubject implements Subject {
    private List<Observer> list = new ArrayList<>();
 
    // 注册观察者
    public void registerObserver(Observer observer) {
        list.add(observer);
    }
 
    // 移除观察者
    public void removeObserver(Observer observer) {
        list.remove(observer);
    }
 
    // 通知观察者
    public void notifyObserver(String message) {
        for (Observer observer : list) {
            observer.update(message);
        }
    }
}

在上面的代码中,我们有观察者接口 Observer 和具体实现的两个观察者 ConcreteObserver1ConcreteObserver2。还有主题接口 Subject,它有三个方法:registerObserverremoveObservernotifyObserver,用于注册观察者、移除观察者和通知观察者。最后,我们有一个具体的主题 ConcreteSubject,它维护了 Observer 对象的列表,实现了 Subject 接口中的三个方法。

以下是使用Java观察者模式的示例代码:

public class ObserverTest {
    public static void main(String[] args) {
        ConcreteSubject subject = new ConcreteSubject(); // 创建具体主题
        Observer observer1 = new ConcreteObserver1(); // 创建具体观察者1
        Observer observer2 = new ConcreteObserver2(); // 创建具体观察者2
        subject.registerObserver(observer1); // 注册观察者1
        subject.registerObserver(observer2); // 注册观察者2
        subject.notifyObserver("观察者模式测试"); // 通知所有观察者
    }
}

在测试代码中,我们创建了一个具体主题 ConcreteSubject 和两个具体观察者 ConcreteObserver1ConcreteObserver2。它们的行为是在主题状态改变之后被调用。我们注册了这两个观察者,并用 notifyObserver() 方法通知它们主题状态已经改变。

在观察者模式中,主题和观察者的分离使代码具有更好的松耦合性,使得对象之间可以更加灵活地交互和协作。文章来源地址https://www.toymoban.com/news/detail-507766.html

到了这里,关于Java七种常用设计模式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 大话设计模式——9.单例模式(Singleton Pattern)

    简介 确保一个类只有一个实例,并提供全局访问点来获取该实例,是最简单的设计模式。 UML图: 单例模式共有两种创建方式: 饿汉式(线程安全) 提前创建实例,好处在于该实例全局唯一,不存在线程冲突;坏处在于未使用时也会占用内存资源。 懒汉式(原生写法存在线

    2024年04月12日
    浏览(34)
  • 《golang设计模式》第一部分·创建型模式-01-单例模式(Singleton)

    指目标类(Class)只有一个实例对象(Object),并且向使用该对象的客户端提供访问单例的全局方法。 保证类只有一个实例 有方法能让外部访问到该实例 懒汉式 在第一次调用单例对象时创建该对象,这样可以避免不必要的资源浪费 饿汉式 在程序启动时就创建单例对象,这

    2024年02月14日
    浏览(37)
  • Singleton 单例模式简介与 C# 示例【创建型】【设计模式来了】

    一句话解释:   单一的类,只能自己来创建唯一的一个对象。 单例模式(Singleton Pattern)是日常开发中最简单的设计模式之一。这种类型的设计模式属于 创建型模式 ,它提供了一种创建对象的最佳方式。 这种模式涉及到一个 单一的类 ,该类负责 创建自己的对象 ,同时

    2024年02月06日
    浏览(29)
  • 七种常用的设计模式

    常用的七种设计模式:单例模式、工厂方法模式、抽象工厂模式、代理模式、装饰器模式、观察者模式和责任链模式。 设计模式分类 设计模式根据工作的目的,分为创建型模式、结构型模式和行为型模式三类。 创建型模式: 单例模式 、 工厂方法模式 、 抽象工厂模式 、创

    2024年02月01日
    浏览(25)
  • 【设计模式】单例模式|最常用的设计模式

    单例模式是最常用的设计模式之一,虽然简单,但是还是有一些小坑点需要注意。本文介绍单例模式并使用go语言实现一遍单例模式。 单例模式保证一个类仅有一个实例,并提供一个访问它的全局访问点。 使用场景: 当类只能有一个实例而且可以从一个公开的众所周知的访

    2024年04月29日
    浏览(34)
  • 【Java面试题】设计模式之七种结构性模式——代理模式、适配器模式、桥接模式、装饰模式、外观模式、享元模式、组合模式

    目录 一、代理模式 二、适配器模式 三、桥接模式 四、装饰模式 五、外观模式 六、享元模式 七、组合模式 概念: 代理模式是为其他对象提供一种以代理控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对

    2023年04月09日
    浏览(41)
  • Java设计模式【单例模式】

    单例模式(Singleton Pattern)是一种创建型设计模式,其主要目的是确保一个类只有一个实例,并提供对该实例的唯一访问点。 优点 : 提供了对唯一实例的受控访问。 由于在系统内存中只存在一个对象,因此可以节约系统资源。 缺点 : 单例类的扩展有很大的困难。 单例类的

    2024年02月04日
    浏览(52)
  • 【java】设计模式——单例模式

    单例模式要点 : 一个类只需要一个实例化对象; 必须自行创建实例; 必须自行向整个系统提供这个实例 实现 : 只提供 私有 构造方法; 有一个该类的 静态 私有对象; 提供一个静态 公有 方法用于创建、获取静态私有对象; 分析: 私有构造方法-不能随意创建实例; 静态

    2024年02月13日
    浏览(32)
  • JAVA设计模式——单例模式

    单例模式是应用最广的设计模式之一,也是程序员最熟悉的一个设计模式,使用单例模式的类必须保证只能有创建一个对象。 今天主要是回顾一下单例模式,主要是想搞懂以下几个问题 为什么要使用单例? 如何实现一个单例? 单例存在哪些问题? 单例对象的作用域的范围

    2024年02月16日
    浏览(34)
  • Java设计模式-单例模式

    单例模式是一种设计模式,它确保一个类只能创建一个实例,并提供一种全局访问这个实例的方式。在Java中,单例模式可以通过多种方式来实现,其中最常见的是使用私有构造函数和静态方法实现 在Java中,实现单例模式的方式有多种,其中最常见的实现方式包括以下几种:

    2024年02月01日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包