编程-设计模式 25:MVC (Model-View-Controller)模式

设计模式 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模式,它可以帮助你将应用程序的数据层与用户界面层分离,使得应用程序的各个部分可以独立开发和维护。这对于需要将应用程序的逻辑、数据和用户界面分离的场景非常有用。

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值