当前位置: 首页 > news >正文

JavaScript工厂模式

HTTP客户端-工厂模式

class HttpClient {constructor(config) {this.baseURL = config.baseURL;this.timeout = config.timeout;this.headers = config.headers;}async get(url) {// 模拟: HTTP GET 请求console.log(`GET ${this.baseURL}${url}`);return { data: 'mock data' };}
}class HttpClientFactory {static createClient(type) {const configs = {api: {baseURL: 'https://api.example.com',timeout: 5000,headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }},upload: {baseURL: 'https://upload.example.com',timeout: 30000,headers: { 'Content-Type': 'multipart/form-data' }},analytics: {baseURL: 'https://analytics.example.com',timeout: 2000,headers: { 'X-API-Key': process.env.ANALYTICS_API_KEY }}};const config = configs[type];if (!config) {throw new Error(`不支持的客户端类型: ${type}`);}return new HttpClient(config);}
}// 使用:客户端代码完全解耦
const apiClient = HttpClientFactory.createClient('api');
const uploadClient = HttpClientFactory.createClient('upload');apiClient.get('/users');
uploadClient.get('/files');

表单验证器-工厂模式

class EmailValidator {validate(value) {const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);return { valid, message: valid ? '' : '请输入有效的邮箱地址' };}
}class PhoneValidator {validate(value) {const valid = /^1[3-9]\d{9}$/.test(value);return { valid, message: valid ? '' : '请输入有效的手机号码' };}
}class ValidatorFactory {static createValidator(type) {const validators = {email: () => new EmailValidator(),phone: () => new PhoneValidator(),};const factory = validators[type];if (!factory) {throw new Error(`不支持的验证器类型: ${type}`);}return factory();}
}// 使用:统一的验证接口
const emailValidator = ValidatorFactory.createValidator('email');
const phoneValidator = ValidatorFactory.createValidator('phone');console.log(emailValidator.validate('test@example.com'));
console.log(phoneValidator.validate('13800138000'));

React组件-工厂模式

// 基础组件
const Button = ({ variant, children, ...props }) => {const classes = {primary: 'bg-blue-500 text-white',secondary: 'bg-gray-500 text-white'};return (<button className={`px-4 py-2 rounded ${classes[variant]}`} {...props}>{children}</button>);
};const Input = ({ error, ...props }) => (<div><inputclassName={`border rounded px-3 py-2 ${error ? 'border-red-500' : 'border-gray-300'}`}{...props}/>{error && <p className="text-red-500 text-sm mt-1">{error}</p>}</div>
);// 组件工厂
class ComponentFactory {static components = {button: Button,input: Input,};static createComponent(type, props) {const Component = this.components[type];if (!Component) {throw new Error(`不支持的组件类型: ${type}`);}return React.createElement(Component, props);}
}// 使用
const MyForm = () => {return (<div>{ComponentFactory.createComponent('input', { placeholder: '请输入用户名' })}{ComponentFactory.createComponent('button', { variant: 'primary',children: '提交'})}</div>);
};

https://juejin.cn/post/7541039466799071272 稀土掘金

http://www.dtcms.com/a/353951.html

相关文章:

  • 鸿蒙、安卓系统如何体验谷歌服务?实用方法分享
  • LangGraph - API多种访问方式
  • Docker 入门指南:从基础概念到常见命令及高级工具详解
  • Transformer 模型详解
  • [Sync_ai_vid] 唇形同步评判器 | 图像与视频处理器 | GPU测试
  • 为什么 “int ” 会变成 “int”?C++ 引用折叠的原理与本质详解
  • nacos2.4.1版本开启鉴权
  • SmartMediakit视角构建低空经济的超低延迟视频基础设施
  • git学习 分支管理(branching)合并分支
  • 鸿蒙清楚本地缓存
  • AI大语言模型助力:国自然/省级基金项目撰写(如何高效准备申请材料?如何精准把握评审标准?从申请者和评审者的不同角度全解
  • 【单例模式】
  • CUDA的编译与调试
  • Mac 上录制视频有几种常见方式
  • 基于springboot的校园资料分享平台(源码+论文+PPT答辩)
  • 网络安全监控中心
  • 【笔记】Windows 安装 Triton 的工作记录(之二)
  • IDR的RWA金融逻辑RWA:全球金融革命的底层协议
  • 数学建模——马尔科夫链(Markov Chain Model)
  • 集成学习之 Stacking(堆叠集成)
  • django配置多个app使用同一个static静态文件目录
  • 使用openCV(C ++ / Python)的Alpha混合
  • 【高级机器学习】 2. Loss Functions(损失函数)
  • 一、快速掌握Python 中的文件操作知识体系
  • mysql zip包安装步骤
  • 2025(秋)中国国际健康产业(成都)博览会:探索健康未来辉煌
  • TCP 并发服务器构建
  • 场外期权能做套利吗?
  • 二叉树的工程实践与高频问题(续):从LeetCode真题到系统设计的深度剖析
  • centos7 安装指定版本的fastfds