下面是一个 Solidity 合约的示例,它是一种工厂模式 native 方法,可将船员添加到矩阵中的 neb 星舰中。
该契约(Contract)的克隆工厂版本是什么?
// SPDX-License-Identifier: MIT
pragma solidity >0.4.23 <0.9.0;
contract NebCrewFactory {
//Creating an array of neb crew addresses
NebCrew[] public NebCrewAddresses;
function addNebCrew() public {
//Creating a new crew object, you need to pay //for the deployment of this contract everytime - $$$$
NebCrew nebCrewAddress = new NebCrew();
//Adding the new crew to our list of crew addresses
NebCrewAddresses.push(nebCrewAddress);
}
}
contract NebCrew{
address public crew;
constructor() {
crew = msg.sender;
}
function welcomeCrew() public pure returns (string memory _greeting) {
return "Welcome to the truth...";
}
}
最佳答案
我展示的克隆工厂版本使用 OpenZeppelin 库 here
// SPDX-License-Identifier: MIT
pragma solidity >0.4.23 <0.9.0;
import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";
contract NebCrewFactory {
//Creating an array of neb crew addresses
NebCrew[] public NebCrewAddresses;
address public implementationAddress;
function addNebCrew() public {
//Creating a new crew object, you need to pay //for the deployment of this contract everytime - $$$$
NebCrew nebCrewAddress = NewCrew(Clones.clone(implementationAddress));
// since the clone create a proxy, the constructor is redundant and you have to use the initialize function
nebCrewAddress.initialize();
//Adding the new crew to our list of crew addresses
NebCrewAddresses.push(nebCrewAddress);
}
}
contract NebCrew{
address public crew;
initialize() {
require(crew == address(0), "already initialized");
crew = msg.sender;
}
function welcomeCrew() public pure returns (string memory _greeting) {
return "Welcome to the truth...";
}
}
也无关,但我想提一下,如果可以的话,最好在工厂中使用映射而不是数组,因为它可能会在将来引起问题
关于design-patterns - Solidity - 从工厂模式到克隆工厂模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71405290/