Bird
Raised Fist0
Blockchain / Solidityprogramming~15 mins

Factory pattern in Blockchain / Solidity - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Factory pattern
What is it?
The Factory pattern is a way to create objects in programming without specifying the exact class of the object to create. It provides a method that returns different types of objects based on input or conditions. This helps organize code and makes it easier to add new object types later. In blockchain, it often helps create smart contracts or tokens dynamically.
Why it matters
Without the Factory pattern, developers would have to write repetitive code to create each object type, making the system hard to maintain and extend. In blockchain, where contracts and tokens vary, this pattern allows easy deployment of new contracts without rewriting code. It saves time, reduces errors, and supports scalable decentralized applications.
Where it fits
Before learning the Factory pattern, you should understand basic object-oriented programming concepts and how smart contracts work in blockchain. After mastering it, you can explore advanced design patterns like Singleton or Proxy, and learn how to optimize contract deployment and upgradeability.
Mental Model
Core Idea
The Factory pattern is a smart creator that decides which object to make based on your request, hiding the details from you.
Think of it like...
Imagine a vending machine that gives you different snacks depending on the button you press. You don’t need to know how each snack is made, just which button to push.
┌───────────────┐
│   Client      │
└──────┬────────┘
       │ request type
       ▼
┌───────────────┐
│   Factory     │
│ (decides what │
│  to create)   │
└──────┬────────┘
       │ creates
       ▼
┌───────────────┐
│  Product A    │
└───────────────┘

or

┌───────────────┐
│  Product B    │
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding object creation basics
🤔
Concept: Learn how objects are created in blockchain smart contracts and why direct creation can be limiting.
In blockchain, smart contracts are like programs deployed on the network. Each contract can create objects or tokens by writing code. Usually, you write code that directly creates a specific contract or token. For example, deploying a token contract with fixed parameters. But if you want to create many types of tokens or contracts, writing separate code for each is repetitive.
Result
You understand that creating objects directly means repeating code and limits flexibility.
Knowing how direct creation works shows why a pattern that centralizes creation logic can save effort and reduce errors.
2
FoundationIntroducing the Factory pattern concept
🤔
Concept: The Factory pattern centralizes object creation in one place, deciding which object to create based on input.
Instead of creating objects directly, you write a Factory contract that has a function to create different contracts or tokens. The client calls this function with parameters, and the Factory decides which contract to deploy and returns its address. This way, the client doesn’t need to know the details of each contract type.
Result
You can create different contracts by calling one Factory function with different inputs.
Centralizing creation logic makes your code cleaner, easier to maintain, and ready for new contract types.
3
IntermediateImplementing a simple Factory in Solidity
🤔Before reading on: do you think the Factory contract stores all created contracts or just their addresses? Commit to your answer.
Concept: Learn how to write a Factory contract in Solidity that deploys new contracts and keeps track of them.
In Solidity, you can write a Factory contract with a function that uses the 'new' keyword to deploy other contracts. The Factory can store the addresses of created contracts in an array for reference. For example, a TokenFactory creates different token contracts based on parameters like name and symbol.
Result
The Factory contract deploys new token contracts and stores their addresses for later use.
Knowing how to deploy contracts from another contract is key to building flexible blockchain applications.
4
IntermediateHandling multiple product types in Factory
🤔Before reading on: do you think the Factory should use if-else or mapping to decide which contract to create? Commit to your answer.
Concept: Extend the Factory to create different contract types based on input, using control structures.
The Factory function can take a parameter like a string or enum to decide which contract to deploy. Using if-else or switch-like logic, it creates the right contract. For example, if input is 'Token', deploy a token contract; if 'NFT', deploy an NFT contract. This makes the Factory versatile.
Result
The Factory can create multiple contract types from one function call.
Using conditional logic in the Factory allows easy expansion to new contract types without changing client code.
5
IntermediatePassing parameters to created contracts
🤔
Concept: Learn how to send initialization data to new contracts created by the Factory.
When deploying a contract with 'new', you can pass constructor arguments. The Factory function accepts parameters and forwards them to the new contract’s constructor. For example, passing token name and symbol to a token contract. This allows each created contract to have unique properties.
Result
Each contract created by the Factory can be customized with different data.
Passing parameters during creation makes the Factory pattern flexible and powerful for real-world use.
6
AdvancedFactory pattern for upgradeable contracts
🤔Before reading on: do you think the Factory creates upgradeable contracts directly or uses proxies? Commit to your answer.
Concept: Explore how the Factory pattern works with upgradeable contracts using proxy patterns.
In blockchain, contracts are immutable once deployed. To upgrade, developers use proxy contracts that delegate calls to logic contracts. The Factory can deploy proxy contracts pointing to logic contracts, allowing upgrades by changing the logic address. This pattern separates creation from logic, enabling flexible upgrades.
Result
The Factory creates upgradeable proxy contracts, supporting contract evolution without redeployment.
Understanding how Factory works with proxies is crucial for building maintainable, upgradeable blockchain systems.
7
ExpertGas optimization and security in Factory pattern
🤔Before reading on: do you think deploying contracts via Factory costs more or less gas than direct deployment? Commit to your answer.
Concept: Learn advanced techniques to reduce gas costs and improve security when using Factory contracts.
Deploying contracts via Factory adds overhead, but techniques like minimal proxies (EIP-1167) reduce gas by deploying lightweight clones. Also, Factory contracts must validate inputs carefully to avoid creating malicious contracts. Using access control and event logging improves security and traceability.
Result
Factories become efficient and secure, suitable for production blockchain applications.
Mastering gas optimization and security in Factory patterns prevents costly mistakes and vulnerabilities in live systems.
Under the Hood
The Factory contract uses the blockchain's contract creation opcode to deploy new contracts dynamically. When the Factory's create function is called, it executes the 'new' operation with constructor parameters, which stores the new contract's bytecode on-chain and returns its address. The Factory can keep track of these addresses for management. For upgradeable contracts, the Factory deploys proxy contracts that forward calls to logic contracts, separating state and logic.
Why designed this way?
The Factory pattern was designed to solve code duplication and inflexibility in object creation. In blockchain, deploying contracts is costly and immutable, so centralizing creation logic reduces errors and supports scalability. Alternatives like direct deployment lack flexibility, and manual deployment is error-prone. The pattern balances ease of use, extensibility, and security.
┌───────────────┐
│ Client calls  │
│ Factory.create│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Factory uses  │
│ 'new' opcode  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ New Contract  │
│ deployed on   │
│ blockchain    │
└───────────────┘

For upgradeable:

┌───────────────┐
│ Factory deploy│
│ Proxy Contract│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Proxy forwards│
│ calls to      │
│ Logic Contract│
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does the Factory pattern always create new contracts or can it reuse existing ones? Commit to yes or no.
Common Belief:The Factory pattern always creates brand new contracts every time it is called.
Tap to reveal reality
Reality:Factories can create new contracts or deploy minimal proxy clones that reuse existing logic contracts to save gas.
Why it matters:Believing factories always create full new contracts leads to ignoring gas optimization techniques, increasing deployment costs unnecessarily.
Quick: Do you think the Factory pattern hides all contract details from users? Commit to yes or no.
Common Belief:The Factory pattern completely hides the internal workings of created contracts from clients.
Tap to reveal reality
Reality:The Factory hides creation details but clients interact directly with created contracts afterward and must understand their interfaces.
Why it matters:Assuming full hiding can cause confusion when clients try to use contracts without knowing their functions.
Quick: Is the Factory pattern only useful for creating tokens? Commit to yes or no.
Common Belief:Factory pattern is only useful for creating token contracts in blockchain.
Tap to reveal reality
Reality:Factory pattern applies broadly to any contract creation, including NFTs, DAOs, oracles, and upgradeable proxies.
Why it matters:Limiting the pattern to tokens restricts creative uses and reduces architectural flexibility.
Quick: Does using a Factory pattern guarantee security of created contracts? Commit to yes or no.
Common Belief:Using a Factory pattern automatically makes contract creation secure and error-free.
Tap to reveal reality
Reality:Factory contracts must be carefully coded with input validation and access control; otherwise, they can introduce vulnerabilities.
Why it matters:Overconfidence in Factory security can lead to exploits and loss of funds.
Expert Zone
1
Factories can implement event logging for every created contract, enabling off-chain tracking and analytics.
2
Using minimal proxy clones (EIP-1167) in Factory reduces deployment gas costs drastically compared to full contract deployment.
3
Factories can integrate access control to restrict who can create contracts, preventing spam or malicious deployments.
When NOT to use
Avoid Factory pattern when contract creation logic is simple and unlikely to change, or when deployment costs must be minimal without overhead. Alternatives include direct deployment or using scripts off-chain to deploy contracts manually.
Production Patterns
In production, Factories often combine with proxy upgrade patterns to deploy upgradeable contracts. They also emit detailed events for monitoring and integrate with access control modules like OpenZeppelin's Ownable. Factories are used in token launchpads, NFT minting platforms, and DAO creation tools.
Connections
Proxy pattern
Builds-on
Understanding Factory helps grasp how proxies are deployed dynamically to enable contract upgradeability.
Dependency Injection
Similar pattern
Both Factory and Dependency Injection separate creation from usage, improving modularity and testability.
Manufacturing assembly lines (Industrial Engineering)
Analogous process
Just like factories in industry produce products efficiently by standardizing creation steps, software Factory pattern standardizes object creation for efficiency and consistency.
Common Pitfalls
#1Creating contracts without input validation
Wrong approach:function create(string memory type) public { if (keccak256(bytes(type)) == keccak256(bytes("Token"))) { new Token(); } else { new Unknown(); } }
Correct approach:function create(string memory type) public { require( keccak256(bytes(type)) == keccak256(bytes("Token")) || keccak256(bytes(type)) == keccak256(bytes("NFT")), "Invalid type" ); if (keccak256(bytes(type)) == keccak256(bytes("Token"))) { new Token(); } else { new NFT(); } }
Root cause:Not validating inputs allows creation of unintended or malicious contracts, risking security and wasting gas.
#2Storing created contracts in a local variable only
Wrong approach:function createToken() public { Token token = new Token(); // no storage of token address }
Correct approach:Token[] public tokens; function createToken() public { Token token = new Token(); tokens.push(token); }
Root cause:Failing to store created contract addresses makes it impossible to track or interact with them later.
#3Not restricting who can create contracts
Wrong approach:function createToken() public { new Token(); }
Correct approach:address owner; modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _; } function createToken() public onlyOwner { new Token(); }
Root cause:Allowing anyone to create contracts can lead to spam, high gas costs, or malicious contract deployment.
Key Takeaways
The Factory pattern centralizes and abstracts contract creation, making blockchain applications more modular and maintainable.
It supports creating multiple contract types dynamically, passing parameters to customize each instance.
Using Factory with proxy patterns enables upgradeable contracts, essential for evolving blockchain systems.
Security and gas efficiency require careful Factory design, including input validation, access control, and minimal proxy usage.
Understanding Factory pattern connects to broader software design principles and real-world manufacturing processes.

Practice

(1/5)
1.

What is the main purpose of the Factory pattern in blockchain development?

easy
A. To create multiple similar contracts easily and manage their addresses
B. To encrypt data on the blockchain
C. To mine new blocks faster
D. To validate transactions off-chain

Solution

  1. Step 1: Understand the Factory pattern role

    The Factory pattern is used to create many similar contracts efficiently.
  2. Step 2: Identify its key feature

    It also stores the addresses of these created contracts for easy access later.
  3. Final Answer:

    To create multiple similar contracts easily and manage their addresses -> Option A
  4. Quick Check:

    Factory pattern = create and manage contracts [OK]
Hint: Factory pattern creates and tracks contracts easily [OK]
Common Mistakes:
  • Confusing factory with encryption or mining
  • Thinking factory validates transactions
  • Assuming factory works off-chain
2.

Which of the following is the correct Solidity syntax to deploy a new contract inside a factory contract?

function create() public returns (address) {
    address newContract = new ?();
    return newContract;
}
easy
A. ContractName
B. contractname
C. new ContractName()
D. ContractName()

Solution

  1. Step 1: Recall Solidity contract creation syntax

    To create a new contract instance, use new ContractName().
  2. Step 2: Match syntax with code snippet

    The placeholder new ?() expects the contract name without 'new' repeated.
  3. Final Answer:

    ContractName -> Option A
  4. Quick Check:

    Use 'new ContractName()' but only 'ContractName' inside parentheses [OK]
Hint: Use contract name only inside new keyword parentheses [OK]
Common Mistakes:
  • Writing 'new' twice
  • Using lowercase contract names
  • Omitting parentheses
3.

Consider this Solidity factory contract snippet:

contract Simple {
    uint public value;
    constructor(uint _value) {
        value = _value;
    }
}

contract Factory {
    Simple[] public simples;
    function createSimple(uint _val) public {
        Simple s = new Simple(_val);
        simples.push(s);
    }
    function getValue(uint index) public view returns (uint) {
        return simples[index].value();
    }
}

What will getValue(0) return after calling createSimple(42) once?

medium
A. Address of the contract
B. 0
C. 42
D. Compilation error

Solution

  1. Step 1: Understand contract creation and storage

    Calling createSimple(42) creates a new Simple contract with value = 42 and stores it in simples array.
  2. Step 2: Check what getValue(0) returns

    It returns the value of the first Simple contract, which is 42.
  3. Final Answer:

    42 -> Option C
  4. Quick Check:

    Created contract value = 42 [OK]
Hint: Created contract stores value; getValue returns it [OK]
Common Mistakes:
  • Confusing contract address with stored value
  • Assuming default zero value
  • Thinking it returns array length
4.

Identify the error in this factory contract code snippet:

contract Product {
    uint public id;
    constructor(uint _id) {
        id = _id;
    }
}

contract ProductFactory {
    Product[] public products;
    function createProduct(uint _id) public {
        Product p = Product(_id);
        products.push(p);
    }
}
medium
A. Array products should be a mapping
B. Missing new keyword when creating Product
C. Constructor should not have parameters
D. Function createProduct must be view

Solution

  1. Step 1: Check contract instantiation syntax

    In Solidity, to create a new contract instance, you must use the new keyword.
  2. Step 2: Identify the missing keyword

    The line Product p = Product(_id); misses new, it should be Product p = new Product(_id);.
  3. Final Answer:

    Missing new keyword when creating Product -> Option B
  4. Quick Check:

    Contract creation requires 'new' keyword [OK]
Hint: Always use 'new' to create contracts in Solidity [OK]
Common Mistakes:
  • Forgetting 'new' keyword
  • Changing array to mapping unnecessarily
  • Marking create function as view incorrectly
5.

You want to build a factory contract that creates multiple token contracts with different initial supplies and keeps track of them. Which approach best applies the factory pattern to save gas and organize your project?

hard
A. Use a single token contract and change its supply dynamically for each user
B. Deploy all token contracts manually and hardcode their addresses in the factory
C. Create token contracts but do not store their addresses anywhere
D. Create each token contract separately and store their addresses in an array inside the factory

Solution

  1. Step 1: Understand factory pattern benefits

    The factory pattern helps create many similar contracts and keeps track of them efficiently.
  2. Step 2: Evaluate options for managing multiple tokens

    Creating each token contract inside the factory and storing their addresses allows easy management and gas savings.
  3. Step 3: Reject other options

    Hardcoding addresses is inflexible, using one contract for all tokens breaks isolation, and not storing addresses loses track.
  4. Final Answer:

    Create each token contract separately and store their addresses in an array inside the factory -> Option D
  5. Quick Check:

    Factory creates and tracks contracts for organization [OK]
Hint: Factory creates and stores contracts for easy management [OK]
Common Mistakes:
  • Hardcoding addresses reduces flexibility
  • Using one contract for all tokens causes conflicts
  • Not storing addresses loses track of contracts