method of factory

package methodOfFactory;

public class People
{
private String name;
private String sex;
public People(){}
public People(String name,String sex)
{
this.name = name;
this.sex = sex;
}
public void show(){}
public String toString()
{
return "Name: "+name+" Sex: "+sex;
}
}


package methodOfFactory;

public class Boy extends People {
public Boy(){}
public Boy(String name)
{
super(name,"male");
}
public void show(){}
}


package methodOfFactory;

public class ZhangSan extends Boy {
public ZhangSan()
{
super("zhang san");
}
public void show()
{
System.out.println("zhang san is my dota friend!");
}
}

package methodOfFactory;

public class Girl extends People {
public Girl(){}
public Girl(String name)
{
super(name,"male");
}
public void show(){}

}


package methodOfFactory;

public class LiSi extends Girl {
public LiSi()
{
super("li si");
}
public void show()
{
System.out.println("li si is my girl friend!");
}
}


package methodOfFactory;

public class WangWu extends Girl
{
public WangWu()
{
super("wang wu");
}
public void show()
{
System.out.println("wang wu is my wife!");
}
}


package methodOfFactory;

public interface Factory {
public abstract People getPeople(String name);
}


package methodOfFactory;

public class BoyFactory implements Factory {

@Override
public People getPeople(String name) {
if(name.equalsIgnoreCase("zhangsan"))
{
return new ZhangSan();
}
return null;
}

}


package methodOfFactory;

public class GirlFactory implements Factory
{

@Override
public People getPeople(String name)
{
if(name.equalsIgnoreCase("lisi"))
{
return new LiSi();
}else if(name.equalsIgnoreCase("wangwu"))
{
return new WangWu();
}
return null;
}

}


package methodOfFactory;

public class Main
{

public static void main(String[] args)
{
Factory f = new BoyFactory();
Boy b = (Boy) f.getPeople("zhangsan");
System.out.println(b);
b.show();
Factory fa = new GirlFactory();
Girl g = (Girl) fa.getPeople("lisi");
System.out.println(g);
g.show();
Girl gg = (Girl) fa.getPeople("wangwu");
System.out.println(gg);
gg.show();
}

}
/*
*工厂方法模型就要解决的是有多个工厂,每一个工厂生产特定产品,都是在工厂里面产生对象
*以后凡是要增加其他类型的产品的时候就可以新建一个工厂继承父工厂,然后在新建产品类就
*行,这样很好的体现了Java的一个设计原则,开闭原则
* */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值