Fullstar

Archives

  • December 2025
  • August 2024
  • July 2024
  • February 2024
  • November 2023
  • August 2023
  • July 2023
  • January 2023
  • November 2022
  • October 2022
  • September 2022
  • February 2022
  • January 2022
  • September 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020

Categories

  • Code
  • Lens
  • Life
0
Fullstar
  • Code

设计模式-工厂模式

  • September 9, 2020
  • Brandon
Total
0
Shares
0
0
0

一.工厂模式结构示例

工厂模式示例

定义一个创建产品的接口(顶层工厂类),而由该接口的子类(具体工厂类),决定具体实例化哪种产品。即将产品的实例化延迟到接口的子类(具体工厂类)中。也称多态性工厂方法模式或虚拟构造子模式

二.代码示例

public class Main {
    public static void main(String[] args){
        Client client = new Client();
        client.CreateAndUse(new FactoryCat());
    }

}
class Client{
    public void CreateAndUse(Factory factory){
        IAnimal iAnimal = factory.CreateAnimal();
        iAnimal.Sale();
    }
}
abstract class Factory{
    abstract IAnimal CreateAnimal();
}//工厂基类

class FactoryDog extends Factory{
    IAnimal CreateAnimal(){
        return new Dog();
    }
}
class FactoryCat extends Factory{
    IAnimal CreateAnimal(){
        return new Cat();
    }
}

class FactoryFish extends Factory{
    IAnimal CreateAnimal(){
        return new Fish();
    }
}

interface IAnimal{
    void Sale();
}
class Dog implements IAnimal{
    public void Sale(){
        System.out.println("sale dog");
    }
}
class Cat implements IAnimal{
    public void Sale(){
        System.out.println("sale cat");
    }
}
class Fish implements IAnimal{
    public void Sale(){
        System.out.println("sale fish");
    }
}

三.简单工厂模式

简单工厂模式也称为静态工厂模式,且有时工程类可以简单移入产品类中。如下为单产品重载构造函数下应用简单工厂方法示例

class Product{
public:
    static Product CreateNormalProduct(int num);
    static Product CreateFloatProduct(int num,float );
    static Product CreateSpecialProduct(Some& one);
protected:
    Product(int num);
    Product(int num,float a);
    Product(Some& para);
};
Total
0
Shares
Share 0
Tweet 0
Pin it 0
Brandon

Previous Article
  • Code

汇编基础:常用指令(X86)

  • August 28, 2020
  • Brandon
View Post
Next Article
  • Code

设计模式-单例模式

  • September 10, 2020
  • Brandon
View Post
You May Also Like
View Post
  • Code

Letta部署记录

  • Brandon
  • December 26, 2025
View Post
  • Code

WordPress 后台任务利器:使用 BGRunner 构建可靠的异步处理

  • Brandon
  • December 14, 2025
View Post
  • Code

WordPress image offload

  • Brandon
  • December 14, 2025
View Post
  • Code

ComfyUI应用手册

  • Brandon
  • December 6, 2025
View Post
  • Code

Leetcode Java常用代码

  • Brandon
  • February 17, 2024
View Post
  • Code

Golang入门

  • Brandon
  • February 4, 2024
View Post
  • Code

Setting Up and Maintaining a Ubuntu Environment for My Home Server

  • Brandon
  • November 24, 2023
View Post
  • Code

Swift Learning Log

  • Brandon
  • August 31, 2023

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Fullstar

Input your search keywords and press Enter.