Java 接口工厂案例

接口是实现多重继承的途径,而生成遵循某个接口的对象的典型方式就是工厂方法设计模式。这与直接调用构造器不同,我们在工厂对象上调用的是创建方法,而该工厂对象将生成接口的某个实现的对象。

代码:

interface Cycle {
	void name();
}

interface CycleFactory {
	Cycle getCycle();
}

class Unicycle implements Cycle {

	@Override
	public void name() {
		// TODO Auto-generated method stub
		System.out.println("Unicycle!");
	}
}
class UnicycleFactory implements CycleFactory {

	@Override
	public Cycle getCycle() {
		// TODO Auto-generated method stub
		return new Unicycle();
	}
}

class Bicycle implements Cycle {

	@Override
	public void name() {
		// TODO Auto-generated method stub
		System.out.println("Bicycle!");
	}
}
class BicycleFactory implements CycleFactory {

	@Override
	public Cycle getCycle() {
		// TODO Auto-generated method stub
		return new Bicycle();
	}
}

class Tricycle implements Cycle {

	@Override
	public void name() {
		// TODO Auto-generated method stub
		System.out.println("Tricycle!");
	}
}
class TricycleFactory implements CycleFactory {

	@Override
	public Cycle getCycle() {
		// TODO Auto-generated method stub
		return new Tricycle();
	}
	
}

public class Cycles {
	public static void getCycles(CycleFactory factory) {
		Cycle c = factory.getCycle();
		c.name();
	}
	public static void main(String[] args) {
		getCycles(new UnicycleFactory());
		getCycles(new BicycleFactory());
		getCycles(new TricycleFactory());
	}
}

 通过这种方式,我们就可以创建不同的自行车来复用这段代码。

 来自 ----- Thinking For Java.

上一篇:ORA-12850


下一篇:python – 如何检查循环范围的重叠(重叠的年度循环周期)