Skip to content

Commit b4f65ab

Browse files
committed
Add study notes for 2025-08-20
1 parent 06e7316 commit b4f65ab

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Ttllboy.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,53 @@ timezone: UTC+8
1515
## Notes
1616

1717
<!-- Content_START -->
18+
# 2025-08-20
19+
20+
Solidity 工厂模式学习笔记
21+
一、定义与概念
22+
在 Solidity 中,工厂模式是一种创建型设计模式。它主要用于创建其他合约实例,就像是一个 “合约生成器”。通过工厂合约,可以在运行时动态创建新的合约,并对这些新创建的合约进行管理和配置。
23+
二、使用场景
24+
批量创建合约:当需要创建大量相似功能的合约时,比如创建多个具有相同业务逻辑但参数配置不同的 Token 合约,工厂模式可以简化创建流程。
25+
动态配置合约:根据不同的需求,在创建合约时动态设置合约的初始化参数,例如在创建一个投票合约时,根据投票主题、参与人员等不同信息动态创建不同的投票合约实例。
26+
合约管理:方便对创建的合约进行统一管理,比如记录合约的地址、创建时间等信息,还可以提供一些方法来调用或销毁创建的合约。
27+
三、代码示例
28+
(一)被创建的合约(以简单的计数器合约为例)
29+
solidity
30+
contract Counter {
31+
uint256 public count;
32+
33+
constructor() {
34+
count = 0;
35+
}
36+
37+
function increment() public {
38+
count++;
39+
}
40+
}
41+
(二)工厂合约
42+
solidity
43+
contract CounterFactory {
44+
// 用于存储创建的 Counter 合约地址
45+
address[] public createdCounters;
46+
47+
// 创建 Counter 合约的函数
48+
function createCounter() public {
49+
Counter newCounter = new Counter();
50+
createdCounters.push(address(newCounter));
51+
}
52+
53+
// 获取创建的 Counter 合约数量
54+
function getCounterCount() public view returns (uint256) {
55+
return createdCounters.length;
56+
}
57+
58+
// 调用某个 Counter 合约的 increment 函数
59+
function incrementCounter(uint256 index) public {
60+
require(index < createdCounters.length, "Index out of bounds");
61+
Counter(address(createdCounters[index])).increment();
62+
}
63+
}
64+
1865
# 2025-08-19
1966

2067
单元测试覆盖

0 commit comments

Comments
 (0)