Concept Flow - Factory pattern
Start
Call Factory
Factory creates new contract
Return new contract address
Use new contract
End
The factory pattern creates new contracts on demand and returns their addresses for use.
contract SimpleContract {
uint public value;
constructor(uint _value) { value = _value; }
}
contract Factory {
SimpleContract[] public contracts;
function create(uint _value) public {
SimpleContract c = new SimpleContract(_value);
contracts.push(c);
}
}| Step | Action | Input | New Contract Created? | Contracts Array Length | Output |
|---|---|---|---|---|---|
| 1 | Call Factory.create | value=10 | Yes | 1 | Address of new SimpleContract #1 |
| 2 | Call Factory.create | value=20 | Yes | 2 | Address of new SimpleContract #2 |
| 3 | Call Factory.create | value=30 | Yes | 3 | Address of new SimpleContract #3 |
| 4 | Read contracts array length | - | - | 3 | 3 |
| 5 | Access SimpleContract #2 value | - | - | - | 20 |
| 6 | Stop | - | - | - | No more actions |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| contracts.length | 0 | 1 | 2 | 3 | 3 |
| SimpleContract #1.value | - | 10 | 10 | 10 | 10 |
| SimpleContract #2.value | - | - | 20 | 20 | 20 |
| SimpleContract #3.value | - | - | - | 30 | 30 |
Factory Pattern in Blockchain: - Factory contract creates new contracts using 'new' - Stores addresses of created contracts in an array - Allows tracking and interacting with multiple contracts - Useful for deploying many similar contracts easily - Access contracts by their stored addresses