design-patterns - Solidity - 从工厂模式到克隆工厂模式

标签 design-patterns ethereum solidity factory-pattern decentralized-applications

下面是一个 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/

相关文章:

Java TCP 服务器-客户端设计方案

ethereum - ERC-721 智能合约一次类型转换 2 个 NFT

Solidity 解析器错误 : Expected ';' but got '{'

ios - 定制的、可重复使用的动画代码应该放在哪里?

design-patterns - 是否应该严格执行设计模式?

javascript - 获取另一个合约部署的合约的地址

blockchain - 以太坊智能合约批准另一个合约的支出者

python - 布朗尼/林克比 : Unable to expand environment variable in host setting

ethereum - Uniswap 路由器初始化在代币合约中有何用途

java - 我的代码属于任何设计模式吗?