0
0
Blockchain / Solidityprogramming~5 mins

Factory pattern in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

The factory pattern helps create many similar objects easily without repeating code. It acts like a factory that makes new items when you ask.

When you want to create many similar smart contracts with small differences.
When you want to manage creation of tokens or assets on blockchain.
When you want to keep your code clean by separating creation logic.
When you want to track all created contracts from one place.
When you want to save gas by reusing creation code.
Syntax
Blockchain / Solidity
contract Factory {
    address[] public deployedContracts;

    function createContract() public {
        address newContract = address(new SimpleContract());
        deployedContracts.push(newContract);
    }
}

contract SimpleContract {
    // contract code here
}

The factory contract creates new contracts using new keyword.

It stores addresses of created contracts for easy access.

Examples
This factory creates tokens with different names and keeps their addresses.
Blockchain / Solidity
contract TokenFactory {
    address[] public tokens;

    function createToken(string memory name) public {
        Token newToken = new Token(name);
        tokens.push(address(newToken));
    }
}

contract Token {
    string public name;

    constructor(string memory _name) {
        name = _name;
    }
}
This factory creates wallets owned by the caller and tracks them.
Blockchain / Solidity
contract WalletFactory {
    address[] public wallets;

    function createWallet() public {
        Wallet wallet = new Wallet(msg.sender);
        wallets.push(address(wallet));
    }
}

contract Wallet {
    address public owner;

    constructor(address _owner) {
        owner = _owner;
    }
}
Sample Program

This factory creates SimpleContract instances with a message. It stores their addresses so you can find all created contracts.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract SimpleContract {
    string public message;

    constructor(string memory _message) {
        message = _message;
    }
}

contract Factory {
    address[] public deployedContracts;

    function createSimpleContract(string memory _message) public {
        SimpleContract newContract = new SimpleContract(_message);
        deployedContracts.push(address(newContract));
    }

    function getDeployedContracts() public view returns (address[] memory) {
        return deployedContracts;
    }
}
OutputSuccess
Important Notes

Each new contract costs gas to deploy, so use factories to organize creation.

Factory pattern helps keep blockchain projects modular and easier to maintain.

Summary

The factory pattern creates many similar contracts easily.

It stores addresses of created contracts for tracking.

It keeps your blockchain code clean and organized.