工厂模式简单实现

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();
	}
}

猜你喜欢

转载自blog.csdn.net/s_pr1te/article/details/89675579