简单工厂模式
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为皮鞋,获取皮鞋对象,之后运行穿皮鞋方法。