设计模式 25:MVC (Model-View-Controller)模式
定义与目的
- 定义:MVC 模式是一种软件架构模式,它将应用程序分为三个核心组件:模型(Model)、视图(View)和控制器(Controller)。这种模式有助于分离应用程序的不同方面,提高可维护性和可扩展性。
- 目的:该模式的主要目的是通过将应用程序的数据层与用户界面层分离,使得应用程序的各个部分可以独立开发和维护。
实现示例
假设我们有一个简单的在线商店应用,我们需要展示商品列表,并允许用户下单购买。我们可以使用MVC模式来实现这个需求。
// 模型 - 商品
class Product {private String name;private double price;public Product(String name, double price) {this.name = name;this.price = price;}public String getName() {return name;}public double getPrice() {return price;}
}// 模型 - 商品列表
class ProductList {private List<Product> products = new ArrayList<>();public void addProduct(Product product) {products.add(product);}public List<Product> getProducts() {return products;}
}// 控制器 - 商品控制器
class ProductController {private ProductList productList;public ProductController(ProductList productList) {this.productList = productList;}public List<Product> fetchProducts() {return productList.getProducts();}public void addProduct(Product product) {productList.addProduct(product);}
}// 视图 - 商品列表视图
class ProductListView {private ProductController controller;public ProductListView(ProductController controller) {this.controller = controller;}public void displayProducts() {List<Product> products = controller.fetchProducts();for (Product product : products) {System.out.println("Name: " + product.getName() + ", Price: $" + product.getPrice());}}
}// 客户端代码
public class Client {public static void main(String[] args) {ProductList productList = new ProductList();ProductController productController = new ProductController(productList);ProductListView productListView = new ProductListView(productController);productController.addProduct(new Product("Apple", 0.5));productController.addProduct(new Product("Banana", 0.3));productListView.displayProducts();}
}
使用场景
- 当你需要将应用程序的逻辑、数据和用户界面分离时。
- 当你需要提高应用程序的可维护性和可扩展性时。
- 当你需要支持不同的视图展示相同的数据时。
MVC模式通过将应用程序分为模型、视图和控制器三个核心组件,有助于分离应用程序的不同方面,提高可维护性和可扩展性。这对于需要将应用程序的逻辑、数据和用户界面分离的场景非常有用。
小结
MVC模式是一种常用的J2EE模式,它可以帮助你将应用程序的数据层与用户界面层分离,使得应用程序的各个部分可以独立开发和维护。这对于需要将应用程序的逻辑、数据和用户界面分离的场景非常有用。