Java 多例设计模式
/**
* 多例设计模式:可以根据输入的参数不同返回不同的实例化对象
* 1、构造私有化
* 2、输入的参数不同
* 2017-09-11
* @author Junwei Zhu
*
*/
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)//java8以后可以判断String类型
{
case 1 : return MALE ;
case 2 : return FEMALE;
default : return null;
}
}
public String toString()//取得对象的信息
{
return this.title ;
}
}
public class TestMultiton
{
public static void main(String[] args)
{
Sex s = Sex.getInstance(1);
System.out.println(s.toString());
}
}
---------------
我每一次回头,都感觉自己不够努力,所以我不再回头。
---------------