simple factory

package simpleFactory;

public class Girl
{
public String name;
public int age;
public Girl(){}
public Girl(String name,int age)
{
this.name = name;
this.age = age;
}
public String toString()
{
return "name:"+name+"  age:"+age+"   function:"+function();
}
public String function()
{
return null;
}
}



package simpleFactory;

public class Wife extends Girl {
public Wife(String name,int age)
{
super(name,age);
}
public String function()
{
return "洗衣、做饭、带孩子";
}
}


package simpleFactory;

public class Inamorato extends Girl {
public Inamorato(String name,int age)
{
super(name,age);
}
public String function()
{
return "吃,喝,玩,乐";
}
}



package simpleFactory;

public class Factory
{
private String name ;
public Factory(String name)
{
this.name = name;
}

public Girl getGirl()
{
if(name.equals("wife"))
{
return new Wife("青青",23);
}else if(name.equals("inamorato"))
{
return new Inamorato("白白",18);
}else
{
return null;
}
}
}



package simpleFactory;

public class Main{
public static void main(String[] args)
{
Factory f = new Factory("wife");
System.out.println(f.getGirl());
Factory fa = new Factory("inamorato");
System.out.println(fa.getGirl());
}

}
/*
* 简单工厂模式:将客户端与服务端屏蔽了,客服端只要提出需要什么,服务端就会去帮他完成。例如本例
* 客服端需要wife,它就不需要知道这个wife是怎么来的  只是向factory发出一条消息,消息里面包含一个
* 名字wife就可以。但是要是需要一个男性朋友的时候那就比较麻烦了,需要修改factory里的代码,这就
* 违背了开闭原则,所以就得用工厂方法模式去处理。其实可以考虑将factory写成一个单例。
*
*
* */

你可能感兴趣的:(model of design,simple factory)