多例设计模式

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) ;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容