接口+工厂方法设计实现(面向对象程序设计)
2024-01-07 17:52:17
创建一个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;
}
}
文章来源:https://blog.csdn.net/hhxxttx_/article/details/135429730
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!