java单例模式和工厂模式

2,325 阅读2分钟

单例模式

饿汉式

//饿汉式
public class Hungry {
	//浪费空间
	private byte[] data1=new byte[1024*1024];
	private byte[] data2=new byte[1024*1024];
	private byte[] data3=new byte[1024*1024];
	private byte[] data4=new byte[1024*1024];
	private Hungry(){
		
	}
	private final static Hungry HUNGRY=new Hungry();
	public static Hungry getIndtrance(){
		return HUNGRY;
	}
}
  • 构造函数私有化
  • 先创建一个对象

懒汉式

package abc;
//懒汉式
public class LazyMan {
private LazyMan(){
	System.out.println(Thread.currentThread().getName()+"ok");
}
private volatile static LazyMan LazyMan;

 //双重检测模式懒汉式单例 DCL懒汉式
public static LazyMan getInstance(){
	if(LazyMan==null){
		synchronized(LazyMan.class){
			if(LazyMan==null){
				LazyMan=new LazyMan();//不是一个原子性操作所以加上volatile
			/**
			 * 1.分配内存空间
			 * 2.执行构造方法,初始化对象
			 * 3.把这个对象指向这个空间
			 */
			}
		}
	}
	return LazyMan;
}
}
  • 构造函数私有化
  • 加synchronized防止多个线程同时创建对象
  • volatile防止指令重排,保持原子性,防止另一个线程指向空此时LazyMan还没有完成构造

静态内部类

package abc;

public class Hold {
private  Hold(){}
public static Hold getInstace(){
	return InnerClass.HOLD;
}
public static class InnerClass{
	private static final Hold HOLD=new Hold();
}
}

工厂模式

静态工厂模式

1.简单工厂模式

public class CarFactory {
	public static Car getCar(String car){
		if(car.equals("五菱")){
			return new Wuling();
		}else if(car.equals("特斯拉")){
			return new Tesla();
		}else{
			return null;
		}
	}
	
}

2.工厂方法模式

public interface CarFactory {
    Car getCar();
}
public class TeslaFactory implements CarFactory{

	@Override
	public Car getCar() {
		// TODO Auto-generated method stub
		return new Tesla();
	}
}
	Car car=new  TeslaFactory.getCar();

抽象工厂

是生产工厂的超级工厂(接口)

Lambda 表达式

@Test public void test1() { 	
    Runnable runnable = new Runnable() { 		 
        @Override 		
        public void run() { 
            System.out.println("线程启动了");		 	
        } 	
           }; 	
       runnable.run(); 
     }  
  /**
   * 语法格式一:无参数,无返回值
   * 		() -> System.out.println("Hello Lambda!");
   */
	@Test
	public void test2() {
		//“->”左边只有一个小括号,表示无参数,右边是Lambda体(就相当于实现了匿名内部类里面的方法了,(即就是一个可用的接口实现类了。))
	Runnable runnable = ()->System.out.println("线程启动了");	
	runnable.run();
	}