简单工厂模式

工厂模式

抽象动物:

java 复制代码
public abstract class Animal {
    // 动物都要吃饭
    public abstract void eat();
}
java 复制代码
public class Cat extends Animal{
    @Override
    public void eat() {
        System.out.println("小猫吃猫粮");
    }
}
java 复制代码
public class Cat extends Animal{
    @Override
    public void eat() {
        System.out.println("小猫吃猫粮");
    }
}

抽象工厂:

java 复制代码
public abstract class AnimalFactory {
    public abstract Animal createAnimal();
}
java 复制代码
public class CatFacoty extends AnimalFactory{
    @Override
    public Animal createAnimal() {
        return new Cat();
    }
}
java 复制代码
public class DogFactory extends AnimalFactory{
    @Override
    public Animal createAnimal() {
        return new Dog();
    }
}
java 复制代码
public class FactoryTest {
    public static void main(String[] args) {
        AnimalFactory factory = new DogFactory();
        Animal animal = factory.createAnimal();
        animal.eat();

        AnimalFactory factory2 = new CatFacoty();
        Animal animal2 = factory2.createAnimal();
        animal2.eat();
    }
}

在这里,如果需要创建新的类,只需要新增animal的子类和factory的资料,不需要修改原来的代码,对扩展开放,符合开闭原则。

源码参考:

  • Collection.iterator
  • URLStreamHandler.createURLStreamHandler
相关推荐
Risehuxyc1 小时前
PHP能不能在参数里放匿名函数
开发语言·php
码云社区1 小时前
Java家政服务系统源码:人员技能、服务范围与多商家业务落地
java·开发语言·家政服务·家政小程序·家政系统
FRing032 小时前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
摇滚侠2 小时前
《On Java 中文版 基础卷》阅读笔记 接口 18
java·笔记·python
CoderYanger3 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第八弹):MyBatis Generator
java·数据库·spring boot·spring·java-ee·tomcat·mybatis
whitelbwwww3 小时前
CUDA C++实战--中级
开发语言·前端·c++
FungLeo4 小时前
FengCMS · PHP+MySQL 升级实录 · 内容写入一致性:锁等待超时与跨模型子树删除竞态
开发语言·mysql·php·工程实践·fengcms
jaysee-sjc6 小时前
【黑马点评】Day02:优惠券秒杀与分布式锁
java·分布式·nginx·spring·node.js·tomcat·maven
谙弆悕博士6 小时前
多智能体架构详解:市场拍卖式架构(Market-based / 竞价协商)
开发语言·架构·去中心化·多智能体·智能体·拍卖架构
ShineWinsu6 小时前
对于Qt:QMessageBox的解析
开发语言·c++·qt·面试·客户端·qmessagebox·消息对话框