(1)单例饿汉模式://饿汉式单例类.在类初始化时,已经自行实例化
public class Singleton1
{ //私有的默认构造子
private Singleton1() {} //已经自行实例化
private static final Singleton1 single = new Singleton1(); //静态工厂方法
public static Singleton1 getInstance() { return single; } }
(2)懒汉模式://懒汉式单例类.在第一次调用的时候实例化
Java初高级一起学习分享,共同学习才是最明智的选择,喜欢的话可以我的学习群64弍46衣3凌9,或加资料群69似64陆0吧3(进群备注平台名)
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();}}
网友评论