自学内容网 自学内容网

工厂模式与单例模式

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

// 定义产品接口
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
单例模式示例
单例模式示例

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


原文地址:https://blog.csdn.net/weixin_47000834/article/details/138749057

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!