Java之路:多例设计模式(Multiton Pattern)

单例设计模式是只能够存在一个实例化对象,而多例设计模式指的是一个类可以定义指定多个对象,但是不管是单例还是多例,构造方法都不可能使用public定义。

实际上对于多例设计能够体现在很多的方面,例如:现在要定义一个表示一周时间数的类,那么这个类只能够有七个对象。如果定义一个表示性别的类,那么这个类只能有两个对象。例如表示颜色基色的类只有三个对象,这些都属于多例设计模式。下面看一个多例设计的例子:

package com.xy.test3;
class Sex {
	private String title;
	private static final Sex MALE = new Sex("男");
	private static final Sex FEMALE = new Sex("女");
	private Sex(String title) {
		this.title = title;
	}
	
	public static Sex getInstance(int ch) {
		switch(ch) {	
			case 0:	return MALE;
			case 1: return FEMALE;
			default: return null;
		}
	}
	
	public String toString() {
		return this.title;
	}
}
public class MultitonPattern {
	public static void main(String[] args) {
		System.out.println(Sex.getInstance(0));
		System.out.println(Sex.getInstance(1));
	}
}

【结果】
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43555323/article/details/84938732