创建一个Cycle接口及其Unicycle、Bicycle和Tricycle实现。对每种类型的Cycle都创建相应的工厂,然后编写代码使用这些工厂。(工厂产生的对象能被管理,可以输出当前产生的对象总数。
?
public class Bicycle implements Cycle {
@Override
public void ride() {
System.out.println("自行车");
}
}
// BicycleFactory.java
public class BicycleFactory implements CycleFactory {
private static int totalCount = 0;
@Override
public Cycle createCycle() {
totalCount++;
return new Bicycle();
}
@Override
public int getTotalCount() {
return totalCount;
}
}
public interface Cycle {
void ride();
}
public interface CycleFactory {
Cycle createCycle();
int getTotalCount();
}
public class Main {
public static void main(String[] args) {
CycleFactory unicycleFactory = new UnicycleFactory();
CycleFactory bicycleFactory = new BicycleFactory();
CycleFactory tricycleFactory = new TricycleFactory();
Cycle unicycle = unicycleFactory.createCycle();
Cycle bicycle = bicycleFactory.createCycle();
Cycle tricycle = tricycleFactory.createCycle();
unicycle.ride();
bicycle.ride();
tricycle.ride();
System.out.println("总共创建了 " + unicycleFactory.getTotalCount() + " 辆独轮车,"
+ bicycleFactory.getTotalCount() + " 辆自行车," + tricycleFactory.getTotalCount() + " 辆三轮车。");
}
}
public class Tricycle implements Cycle {
@Override
public void ride() {
System.out.println("三轮车");
}
}
// TricycleFactory.java
public class TricycleFactory implements CycleFactory {
private static int totalCount = 0;
@Override
public Cycle createCycle() {
totalCount++;
return new Tricycle();
}
@Override
public int getTotalCount() {
return totalCount;
}
}
public class Unicycle implements Cycle {
@Override
public void ride() {
System.out.println("独轮车");
}
}
public class UnicycleFactory implements CycleFactory {
private static int totalCount = 0;
@Override
public Cycle createCycle() {
totalCount++;
return new Unicycle();
}
@Override
public int getTotalCount() {
return totalCount;
}
}