某造船厂可以根据客户的需求生产集装箱船、客滚船、冷藏船等船舶。用简单工厂模式模拟造船厂对船舶的生产(Java语言),并在组合框中选中想要生产的船舶的种类后用图片显示出所生产的船舶。
时间: 2024-05-16 14:16:43 浏览: 89
一个简单的工厂模式(java)
首先,我们需要定义一个船舶的抽象类 Ship,其中包含船舶的一些基本属性和方法,例如船名、长度、宽度、高度等等:
```java
public abstract class Ship {
protected String name;
protected int length;
protected int width;
protected int height;
public Ship(String name, int length, int width, int height) {
this.name = name;
this.length = length;
this.width = width;
this.height = height;
}
public abstract void display();
}
```
接着,我们需要定义具体的船舶类,例如集装箱船 ContainerShip、客滚船 PassengerShip、冷藏船 RefrigeratedShip 等等,它们都继承自 Ship 抽象类,并实现 display() 方法来显示对应的船舶图片:
```java
public class ContainerShip extends Ship {
public ContainerShip(String name, int length, int width, int height) {
super(name, length, width, height);
}
@Override
public void display() {
// 显示集装箱船的图片
System.out.println("显示集装箱船的图片:" + name);
}
}
public class PassengerShip extends Ship {
public PassengerShip(String name, int length, int width, int height) {
super(name, length, width, height);
}
@Override
public void display() {
// 显示客滚船的图片
System.out.println("显示客滚船的图片:" + name);
}
}
public class RefrigeratedShip extends Ship {
public RefrigeratedShip(String name, int length, int width, int height) {
super(name, length, width, height);
}
@Override
public void display() {
// 显示冷藏船的图片
System.out.println("显示冷藏船的图片:" + name);
}
}
```
现在,我们可以使用简单工厂模式来创建船舶。首先,我们需要定义一个 ShipFactory 工厂类,根据客户的需求来创建对应的船舶对象:
```java
public class ShipFactory {
public static Ship createShip(String type, String name, int length, int width, int height) {
if ("container".equalsIgnoreCase(type)) {
return new ContainerShip(name, length, width, height);
} else if ("passenger".equalsIgnoreCase(type)) {
return new PassengerShip(name, length, width, height);
} else if ("refrigerated".equalsIgnoreCase(type)) {
return new RefrigeratedShip(name, length, width, height);
} else {
throw new IllegalArgumentException("Unsupported ship type: " + type);
}
}
}
```
最后,我们可以使用组合框(JComboBox)来让客户选择要生产的船舶类型,并在选择后创建对应的船舶对象并进行显示:
```java
public class ShipProduction {
public static void main(String[] args) {
// 创建组合框并添加选项
JComboBox<String> comboBox = new JComboBox<>();
comboBox.addItem("Container Ship");
comboBox.addItem("Passenger Ship");
comboBox.addItem("Refrigerated Ship");
// 添加选项监听器
comboBox.addActionListener(e -> {
// 获取选中的船舶类型
String type = (String) comboBox.getSelectedItem();
// 创建对应的船舶对象
Ship ship = ShipFactory.createShip(type.toLowerCase().replace(" ", ""),
"My " + type, 100, 20, 10);
// 显示船舶图片
ship.display();
});
// 显示界面
JFrame frame = new JFrame("Ship Production");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(comboBox, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
```
当客户选择了某个船舶类型后,程序就会创建对应的船舶对象并显示出来。
阅读全文