用Java编写一个包含三种设计模式一种体系结构的简单程序
时间: 2023-09-11 17:09:30 浏览: 96
好的,下面我会为您提供一个简单的Java程序,其中包含了工厂模式、观察者模式、单例模式以及分层体系结构。该程序实现了一个简单的订单处理系统,具体实现如下:
```java
// 订单类
public class Order {
private int orderId;
private String customerName;
private double totalPrice;
public Order(int orderId, String customerName, double totalPrice) {
this.orderId = orderId;
this.customerName = customerName;
this.totalPrice = totalPrice;
}
public int getOrderId() {
return orderId;
}
public String getCustomerName() {
return customerName;
}
public double getTotalPrice() {
return totalPrice;
}
}
// 订单处理器接口
public interface OrderHandler {
void handle(Order order);
}
// 订单处理器实现类1
public class EmailOrderHandler implements OrderHandler {
private static EmailOrderHandler instance = null;
private EmailOrderHandler() {
}
public static EmailOrderHandler getInstance() {
if (instance == null) {
instance = new EmailOrderHandler();
}
return instance;
}
@Override
public void handle(Order order) {
// 发送邮件
System.out.println("向客户 " + order.getCustomerName() + " 发送订单邮件,订单号为 " + order.getOrderId());
}
}
// 订单处理器实现类2
public class SMSOrderHandler implements OrderHandler {
private static SMSOrderHandler instance = null;
private SMSOrderHandler() {
}
public static SMSOrderHandler getInstance() {
if (instance == null) {
instance = new SMSOrderHandler();
}
return instance;
}
@Override
public void handle(Order order) {
// 发送短信
System.out.println("向客户 " + order.getCustomerName() + " 发送订单短信,订单号为 " + order.getOrderId());
}
}
// 订单处理器工厂
public class OrderHandlerFactory {
public static OrderHandler getOrderHandler(String handlerType) {
if ("email".equalsIgnoreCase(handlerType)) {
return EmailOrderHandler.getInstance();
} else if ("sms".equalsIgnoreCase(handlerType)) {
return SMSOrderHandler.getInstance();
} else {
throw new IllegalArgumentException("Unsupported handler type.");
}
}
}
// 订单管理器
public class OrderManager {
private List<OrderHandler> orderHandlers;
public OrderManager(List<OrderHandler> orderHandlers) {
this.orderHandlers = orderHandlers;
}
public void placeOrder(Order order) {
// 处理订单
for (OrderHandler handler : orderHandlers) {
handler.handle(order);
}
}
}
// 应用程序入口
public class Application {
public static void main(String[] args) {
// 创建订单处理器列表
List<OrderHandler> handlers = new ArrayList<>();
handlers.add(OrderHandlerFactory.getOrderHandler("email"));
handlers.add(OrderHandlerFactory.getOrderHandler("sms"));
// 创建订单管理器
OrderManager orderManager = new OrderManager(handlers);
// 创建订单
Order order = new Order(1001, "张三", 1000.0);
// 处理订单
orderManager.placeOrder(order);
}
}
```
在该程序中,工厂模式用于创建订单处理器,单例模式用于保证订单处理器实现类的唯一性,观察者模式用于实现订单处理器的通知机制,分层体系结构用于将程序分解为多个模块以实现松耦合。该程序可以根据客户需求自动发送订单邮件或短信,实现了订单处理的自动化和个性化。
阅读全文