工厂模式与单例模式

以下是一个简单的示例代码,演示了工厂模式和单例模式的用法:

// 定义产品接口
interface Product {
    void use();
}

// 具体产品1
class ConcreteProduct1 implements Product {
    public void use() {
        System.out.println("使用具体产品1");
    }
}

// 具体产品2
class ConcreteProduct2 implements Product {
    public void use() {
        System.out.println("使用具体产品2");
    }
}

// 工厂类
class Factory {
    // 根据类型创建产品对象
    public static Product createProduct(String type) {
        if (type.equals("1")) {
            return new ConcreteProduct1();
        } else if (type.equals("2")) {
            return new ConcreteProduct2();
        } else {
            return null;
        }
    }
}

// 单例类
class Singleton {
    private static Singleton instance = null;
    // 私有构造函数
    private Singleton() {}
    // 获取实例的方法
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
    public void showMessage() {
        System.out.println("单例模式示例");
    }
}

// 主程序
public class Demo {
    public static void main(String[] args) {
        // 使用工厂模式创建产品对象
        Product product1 = Factory.createProduct("1");
        product1.use();

        Product product2 = Factory.createProduct("2");
        product2.use();

        // 使用单例模式
        Singleton singleton1 = Singleton.getInstance();
        singleton1.showMessage();

        Singleton singleton2 = Singleton.getInstance();
        singleton2.showMessage();
    }
}

运行结果:

使用具体产品1
使用具体产品2
单例模式示例
单例模式示例

以上示例中,使用工厂模式创建了具体产品对象,并调用了它们的方法。同时使用了单例模式创建了一个实例,并多次调用了该实例的方法,保证了获取的实例是同一个。

相关推荐

  1. 工厂模式模式

    2024-05-13 04:04:05       33 阅读
  2. 【Python】模式工厂模式

    2024-05-13 04:04:05       34 阅读
  3. 模式模板

    2024-05-13 04:04:05       42 阅读
  4. 常用的设计模式模式工厂模式

    2024-05-13 04:04:05       40 阅读
  5. 设计原则、工厂模式

    2024-05-13 04:04:05       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-13 04:04:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-13 04:04:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-05-13 04:04:05       82 阅读
  4. Python语言-面向对象

    2024-05-13 04:04:05       91 阅读

热门阅读

  1. C#中is,as,using关键字的使用

    2024-05-13 04:04:05       25 阅读
  2. C# 事务- TransactionScop 类 如何使用

    2024-05-13 04:04:05       26 阅读
  3. 监听 Redis key 过期事件无效的问题

    2024-05-13 04:04:05       36 阅读
  4. 《认知觉醒》阅读记录

    2024-05-13 04:04:05       29 阅读
  5. 【GoLang基础】select语句是什么?

    2024-05-13 04:04:05       35 阅读
  6. 31Windows精简系统下载推荐

    2024-05-13 04:04:05       31 阅读