简单工厂模式(Simple Factory)

本文介绍简单工厂模式的设计理念及其在代码中的实现方式。通过抽象产品类、具体产品类及工厂类的角色分配,使得对象的创建与使用职责分离,提高了系统的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单工厂模式

简单工厂模式属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,不属于GoF 23种设计模式之一。

简单工厂模式角色: 抽象产品类、具体产品类、工厂类

在简单工厂模式中将对象的创建与使用职责分离了开来,客户端不再负责对象的创建,而是将这个责任丢给了具体的工厂类,客户端只负责对象的调用,从而明确各个类的职责。符合单一职责原则。

uml类图

这里写图片描述

简单工厂模式代码实现
  • 抽象产品类
package CreatePatterns.SimpleFactoryPattern.Animal;

public abstract class Animal {
    abstract void action();//动作
    abstract void eat();//动物进食
}
  • 具体产品类
package CreatePatterns.SimpleFactoryPattern.Animal;
/*
 * 老虎
 */
public class Tiger extends Animal{
    public void action(){
        System.out.println("老虎running");
    }

    public void eat() {
        System.out.println("老虎吃肉");
    }

}
/*
 * 鹦鹉
 */
public class Parrot extends Animal{
    public void action(){
        System.out.println("鹦鹉Flying");
    }

    public void eat(){
        System.out.println("鹦鹉吃虫子");
    }
}
/*
 * 海豚
 */
public class Dolphin extends Animal{
    public void action(){
        System.out.println("海豚swing");
    }

    public void eat(){
        System.out.println("海豚吃鱼");
    }
}
  • 工厂类
package CreatePatterns.SimpleFactoryPattern.Animal;

public class SimpleFactory {
    //根据参数创建对象
    public static Animal createProduct(String productName){
        if("Tiger".equals(productName)){
            return new Tiger();
        }else if("Dolphin".equals(productName)){
            return new Dolphin();  
        }else if("Parrot".equals(productName)){
            return new Parrot();
        }
        return null;
    }
}

客户端

package CreatePatterns.SimpleFactoryPattern.Animal;
/*
*客户端
*/
public class Client {
    public static void main(String[] args){
        Animal tiger = SimpleFactory.createProduct("Tiger");
        tiger.action();
        Animal dolphin = SimpleFactory.createProduct("Dolphin");
        dolphin.action();
        Animal parrot = SimpleFactory.createProduct("Parrot");
        parrot.action();
    }
}

运行结果
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值