Skip to content

Commit

Permalink
feat: update
Browse files Browse the repository at this point in the history
  • Loading branch information
tong committed Jul 8, 2024
1 parent f03b36e commit e795539
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions dev/content/_posts/computer/Dive Into Design Patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,46 @@ featured: true

## Object

我个人比较喜欢面相对象编程,因为它更符合人类思考模型,一个模块就是物理世界中的Object,它有多个属性和作用。**共创多个类可以完成一件复杂的事情**
当类实例化后也就是这个物质诞生的时间。但用多了之后缺点也很明显,如下 (: 可能不算缺点吧,易用性不太适合初级和中级的程序员。

1. 它对一开始的底层设计模式要求很高。
2. 系统复杂度越高,代码越乱,如果是做业务,你无法控制它们之间的合理性,因为需求就是不合理的。对通过构造,继承,多态等操作完成复杂的调用关系。
3. 不可变性和副作用太多,通常一个功能性对象被多个场景混合使用时就是噩梦的开始... 多个地方不合理的操作一个属性,然后
调用地狱,debug查看调用链。

它比较适合一个脱离于渲染的模块,有固定的运行,销毁逻辑。可被外部调用的生命周期完善的类模块。

## Function

尤其对前端来讲,提高开发体验的最好编程方式就是函数式。`状态默认都是不可变的,简洁,易用性高,关注点都在UI上面`
并且最最最重要的是组合性更高。

```javascript
const cart = [
{ name: 'Laptop', price: 999.99, quantity: 1 },
{ name: 'Mouse', price: 25.50, quantity: 2 },
{ name: 'Keyboard', price: 75.00, quantity: 1 },
{ name: 'Monitor', price: 200.00, quantity: 2 },
{ name: 'USB Cable', price: 10.00, quantity: 5 }
];

// 定义纯函数进行数据变换和过滤
const isExpensive = item => item.price > 50;
const getTotalPrice = item => item.price * item.quantity;
const sum = (acc, price) => acc + price;

// 使用高阶函数进行变换和过滤
const expensiveItems = cart.filter(isExpensive);
const totalPrices = expensiveItems.map(getTotalPrice);
const totalPrice = totalPrices.reduce(sum, 0);

console.log(`Total price of expensive items: $${totalPrice.toFixed(2)}`);

```

这种高阶函数和纯函数的组合是非常清晰,并且是状态安全的,并不像OOP一样,它会有潜在的状态变更风险。

所以拿这种编程范式来说,它再适合渲染不过了。因为渲染周期中最容易维护和调试开发的场景就是状态唯一,

状态不变更。而持久化的状态并不属于渲染逻辑,它只负责取状态,至于状态是什么是通过其他模块构造的。

0 comments on commit e795539

Please sign in to comment.