Java-马士兵设计模式学习笔记-工厂模式-单例及多例

一、单例的作用是用于控制类的生成方式,而不让外部类任意new对象

1.Car.java

import java.util.ArrayList;
import java.util.List;

public class Car {

	//私有化构造函数,防止被外部的类new
	private Car() {
	}

	private static Car car = new Car();						//单例
	private static List<Car> cars = new ArrayList<Car>();	//多例,类似连接池
	
	public static Car getInstance() {
		return car;
	}

	public void run() {
		System.out.println("Car running...............");
	}
	
}

  

2.Test.java

public class Test {
	
	@org.junit.Test
	public void test() {
		Car car = Car.getInstance();
		car.run();
		Car car2 = Car.getInstance();
		System.out.println(car == car2);
		System.out.println(car.equals(car2));
	}
}

  

运行结果:

posted @ 2015-06-18 16:15  shamgod  阅读(671)  评论(0编辑  收藏  举报
haha