package com.zbyf.demo;
//定义一个表示性别的类
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 String toString(){
return this.title ;
}
public static Sex getInstance(int ch) { //返回实例化对象
switch(ch) {
case 1:
return MALE ;
case 2:
return FEMALE ;
default:
return null ;
}
}
}
public class TestDemo {
public static void main(String args[]) {
Sex sex = Sex.getInstance(2);
System.out.println(sex) ;
}
}
package com.zbyf.demo;
//定义一个表示性别的类
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 String toString(){
return this.title ;
}
public static Sex getInstance(String ch) { //返回实例化对象
switch(ch) {
case "man":
return MALE ;
case "woman":
return FEMALE ;
default:
return null ;
}
}
}
public class TestDemo {
public static void main(String args[]) {
Sex sex = Sex.getInstance("man"); //利用接口标记内容取得对象
System.out.println(sex) ;
}
}
利用接口描述内容
package com.zbyf.demo;
interface Choose {
public int MAN = 1 ;
public int WOMAN = 2 ;
}
//定义一个表示性别的类
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 String toString(){
return this.title ;
}
public static Sex getInstance(int ch) { //返回实例化对象
switch(ch) {
case 1:
return MALE ;
case 2:
return FEMALE ;
default:
return null ;
}
}
}
public class TestDemo{
public static void main(String args[]) {
Sex sex = Sex.getInstance(Choose.MAN);
System.out.println(sex) ;
}
}