java 工厂 单例_java 单例模式和工厂模式实例详解

本文详细介绍了Java中的两种单例模式——饿汉式和懒汉式,并通过代码示例展示了其实现方式。同时,还探讨了工厂方法模式,通过接口和实现类展示了如何创建和使用产品对象。这些设计模式在软件开发中有着广泛的应用。
摘要由CSDN通过智能技术生成

单例模式根据实例化对象时机的不同分为两种:一种是饿汉式单例,一种是懒汉式单例。

私有的构造方法

指向自己实例的私有静态引用

以自己实例为返回值的静态的公有的方法

饿汉式单例

public class Singleton {

private static Singleton singleton = new Singleton();

private Singleton(){}

public static Singleton getInstance(){

return singleton;

}

}

懒汉式单例

public class Singleton {

private static Singleton singleton;

private Singleton(){}

public static synchronized Singleton getInstance(){

if(singleton==null){

singleton = new Singleton();

}

return singleton;

}

}

工厂方法模式代码

interface IProduct {

public void productMethod();

}

class Product implements IProduct {

public void productMethod() {

System.out.println("产品");

}

}

interface IFactory {

public IProduct createProduct();

}

class Factory implements IFactory {

public IProduct createProduct() {

return new Product();

}

}

public class Client {

public static void main(String[] args) {

IFactory factory = new Factory();

IProduct prodect = factory.createProduct();

prodect.productMethod();

}

}

抽象工厂模式代码

interface IProduct1 {

public void show();

}

interface IProduct2 {

public void show();

}

class Product1 implements IProduct1 {

public void show() {

System.out.println("这是1型产品");

}

}

class Product2 implements IProduct2 {

public void show() {

System.out.println("这是2型产品");

}

}

interface IFactory {

public IProduct1 createProduct1();

public IProduct2 createProduct2();

}

class Factory implements IFactory{

public IProduct1 createProduct1() {

return new Product1();

}

public IProduct2 createProduct2() {

return new Product2();

}

}

public class Client {

public static void main(String[] args){

IFactory factory = new Factory();

factory.createProduct1().show();

factory.createProduct2().show();

}

}

希望本文对各位朋友有所帮助

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值