首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从工厂模式到克隆工厂模式

从工厂模式到克隆工厂模式
EN

Stack Overflow用户
提问于 2022-03-09 06:44:59
回答 1查看 1.3K关注 0票数 2

下面是一个坚固合同的例子,这是一种工厂模式的原生方法,它将船员添加到矩阵中的neb星舰中。

这个合同的克隆工厂版本是什么?

代码语言:javascript
复制
// 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...";
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-09 14:54:16

我展示的克隆工厂版本使用了OpenZeppelin库这里

代码语言:javascript
复制
// 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...";
    }
}

也不相关,但我想提一下,如果可以的话,最好是在工厂中使用一个映射,而不是一个数组,因为它可能会在将来造成问题。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71405290

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档