Jan 01, 1970
GRASP 是General Responsibility Assignment Software Patterns 的缩写。
class Product { constructor(name, price) { this.name = name; this.price = price; } }
class OrderItem { constructor(product, count) { this.product = product, this.count = count } }
class OrderList { constructor(items) { this.items = items; } }
import { OrderItem } from './OrderItem'; import { OrderList } from './OrderList'; import { Product } from './Product'; const samsung = new Product('Samsung', 200); const apple = new Product('Apple', 300); const lg = new Product('Lg', 150); const samsungOrder = new OrderItem(samsung, 2); const appleOrder = new OrderItem(samsung, 3); const lgOrder = new OrderItem(samsung, 4); const orderList = new OrderList([samsungOrder, appleOrder, lgOrder]);
const totalSum = orderList.reduce((res, order) => { return res + order.product.price * order.count }, 0)
听起来不太好。如果我们想以某种方式添加更多与订单一起使用的逻辑,我们是否也将其放在主文件中?而且,一段时间后,我们的主文件会有很多不同的逻辑,有数千行代码,这真的很糟糕。这种反模式称为God object ,其中 1 个文件包含所有内容。
如果我们想使用信息专家的方法应该怎么做?让我们尝试重复:
class OrderItem { constructor(product, count) { this.product = product, this.count = count } getTotalPrice() { return this.product.price * this.count; } }
class OrderList { constructor(items) { this.items = items; } getTotalPrice() { return this.items.reduce((res, item) => { return res + item.getTotalPrice(); }, 0); } }
import { OrderItem } from './OrderItem'; import { OrderList } from './OrderList'; import { Product } from './Product'; const samsung = new Product('Samsung', 200); const apple = new Product('Apple', 300); const lg = new Product('Lg', 150); const samsungOrder = new OrderItem(samsung, 2); const appleOrder = new OrderItem(samsung, 3); const lgOrder = new OrderItem(samsung, 4); const orderList = new OrderList([samsungOrder, appleOrder, lgOrder]); const totalSum = orderList.getTotalPrice();
遵循上帝原则,我们应该只在使用这些对象的地方创建对象。想象一下,使用我们的应用程序,我们将产品添加到购物车。这就是它的样子:
import { OrderList } from './OrderList'; const cartProducts = [{ name: 'Samsung', price: 200, count: 2 }, { name: 'Apple', price: 300, count: 3 }, {name: 'Lg', price: 150, count: 4 }]; const orderList = new OrderList(cartProducts); const totalPrice = orderList.getTotalPrice();
import { OrderItem } from './OrderItem'; class OrderList { constructor(items) { this.items = items.map(item => new OrderItem(item)); } getTotalPrice() { return this.items.reduce((res, item) => { return res + item.getPrice(); }, 0); } }
import { Product } from './Product'; class OrderItem { constructor(item) { this.product = new Product(item.name, item.price); this.count = item.count; } }
class Product { constructor(name, price) { this.name = name; this.price = price; } }
现在,每个对象只在使用它的地方创建。这就是造物主原则所说的。
我希望这个介绍对你有用,在下一个系列的GRASP 中,我们将介绍其他原则。