手写单例模式(饿汉和饱汉模式)和工厂模式
(1)单例饿汉模式://饿汉式单例类.在类初始化时,已经自行实例化
public class Singleton1
{ //私有的默认构造子
private Singleton1() {} //已经自行实例化
private static final Singleton1 single = new Singleton1(); //静态工厂方法
public static Singleton1 getInstance() { return single; } }
(2)懒汉模式://懒汉式单例类.在第一次调用的时候实例化
public class Singleton2
{ //私有的默认构造子
private Singleton2() {} //注意,这里没有final
private static Singleton2 single=null; //静态工厂方法
public synchronized static Singleton2 getInstance() { if (single == null) { single = new Singleton2(); } return single; } }
(3)工厂模式:
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 product=factory.createProduct(); product.ProductMethod();}}
转载:https://blog.csdn.net/qq_36760873/article/details/101155979
查看评论