OOP真实世界的例子

时间:2013-11-04 02:12:24

标签: c# class oop inheritance

我有一个基本的购物车模型,其产品基于来自数据库的数据,其中包含productID,productName,Price,Stock列。然后我有一个item类,它表示消费者选择使用productID,ProductName,Price订购的商品。然后我有itemOrder类,它使用getPrice()引用带有productID,ProductName,Price和数量的项目。然后有一个Cart类,它保存itemOrder并定义添加和删除itemOrder的方法。

在任何这些课程或典型的购物车系统中,OOP技术在哪里发挥作用。

public class Product
{
    public int productID { get; set; }
    public string productName { get; set; }
    ...
 }
}

public class Item : Product
{

}

public class ItemOrder : Item
{
    public int itemQuantity { get; set; }
    public double getPrice(int quantity, double price)
    {
        return price = price * quantity;
    }

}
public class Cart
{

}

1 个答案:

答案 0 :(得分:3)

OOP不需要继承(例如,参见discussion)。如果你的类隐藏了来自世界的内部细节,提供了一个客户端无法用来打破对象的一致界面,并且每个人都做好了单一的工作,那么你就有OOP(我个人认为)。

如果两个类之间的关系符合Liskov Substitution Principle,则仅使用继承:子项继承自Parent if和仅当 Child是Parent时才继承。例如,当您实现接口时,就调用代码而言,新类就是该接口。

项目,产品和订单是三种不同的东西,它们都不能与其他东西互换。所有三个类都应该存在,但它们不应该通过继承相关联。购物车,物品和订单可以通过引用或遏制而不是通过继承来引用产品和彼此。