多例模式

例如:表示一周时间的类要用多例模式

class Sex{
    private String title ;
    private static final Sex MALE = new Sex("man") ;
    private static final Sex FEMALE = new Sex("woman") ;
    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 TestSex{
    public static void main(String arg[]){
        Sex sex = Sex.getInstance("man");
        System.out.println(sex) ;
    }
}

 

posted @ 2016-01-14 12:53  式微胡不归  阅读(129)  评论(0编辑  收藏  举报