设计模式之简单工厂模式

简单工厂模式

简单工厂UML.png
interface Shoe{
    public void wear();
}

定义鞋类接口,定义公共方法穿鞋子。

class LeatherShoe implements Shoe{
    public LeatherShoe(){
        
    }
    
    public void wear(){
        //穿皮鞋
    }
}

皮鞋实体类

class ClothShoe implements Shoe{
    public ClothShoe(){
        
    }
    
    public void wear(){
        //穿布鞋
    }
}   

布鞋实体类

class ShoeFactory{
    public static Shoe getShoe(String type){
        Shoe mShoe = null;
        if(type.equals("皮鞋")){
            mShoe = new LeatherShoe();
        }else if(type.equals("布鞋")){
            mShoe = new ClothShoe();
        }
        return mShoe;
    }
}

鞋子工厂类

class Client{
    public static void main(String args[]){
        Shoe mShoe;
        mShoe = ShoeFactory.getShoe("皮鞋");
        mShoe.wear();
    }
}   

客户端获取鞋类工厂,根据传入type为皮鞋,获取皮鞋对象,之后运行穿皮鞋方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容