工厂模式简单实现

Factory Method 工厂方法模式——定义一个用于创建对象的接口,让子类决定将哪一个类实例化。Factory Method使一个类的实例化延迟到其子类。

代码实现:

package factory;

public class Fruit {
	private String name;
	private String color;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public Fruit(String name, String color) {
		super();
		this.name = name;
		this.color = color;
	}
	public Fruit() {
		super();
	}
	public void plant(){
		System.out.println("种下一颗"+this.name+"树");
	}
	public void grow(){
		System.out.println(this.name+"树正在成长");
	}
	public void growUp(){
		System.out.println("长出了"+this.color+"的"+this.name);
	}
}

package factory;

public interface FruitFactory {
	public Fruit getFruit();
}

package factory;

public class AppleFactory implements FruitFactory{

	@Override
	public Fruit getFruit() {
		// TODO Auto-generated method stub
		return new Fruit("苹果","红色");
	}

}

package factory;

public class Test {
	public static void main(String[] args) {
		//获得工厂
		FruitFactory ff=new AppleFactory();
		//获得水果
		Fruit f=ff.getFruit();
		f.plant();
		f.grow();
		f.growUp();
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值