Java设计模式—工厂设计模式
2024-10-21 05:36:20
工厂设计模式(减少耦合。通过接口或者工厂类来实现)
耦合性:粘度强(依耐性) Person p = new Person(); //耦合性强
Man p = new Person(); //耦合性弱,Man是接口或其它,Person实现这个接口
简单工厂模式是有一个工厂对象决定创建哪一种产品类的实例。
简单工厂模式是工厂模式家族中最简单有用的模式.以下给出演示样例代码:
/**
* 简单工厂设计模式
* @author Admin
*
*/
public class FactoryDesign { public static void main(String[] args) {
Car car1 = Factory.getCar("small"); //通过接口来接收对象减少依赖度(耦合性)
Car car2 = Factory.getCar("big");
if(car1!=null){
car1.run();
}
if(car2!=null){
car2.run();
}
} } class Factory{ //工厂类,来间接控制生产对象
public static Car getCar(String name){
if(name.equals("small")){
return new smallCar(); //生产小汽车
}else if(name.equals("big")){
return new bigCar(); // 生产大汽车
}else return null;
}
} interface Car{
public void run();
}
class smallCar implements Car{
@Override
public void run() {
System.out.println("小汽车在跑");
}
}
class bigCar implements Car{
@Override
public void run() {
System.out.println("大汽车在跑");
}
}
实验结果:
最新文章
- 使用VS2015进行C++开发的6个主要原因
- 【.net core 跨平台】第一步 在Ubuntu16.04 配置.net core环境
- jQuery代码节选(筛选)
- IOS OC 多任务定时器 NSRunLoop 管理 NSTimer
- Android开发LogCat一直不停输出的解决方法
- const实现
- C# 语音识别
- 通过SQL Server Profiler来监视分析死锁
- How to setup ELM327 Bluetooth WiFi for Android software Torque
- nginx rewrite 参数和例子
- empty函数PHP
- oracle常见为题汇总,以及一个简单数据连接操作工厂
- struts2笔记06-ServletXxxAware接口
- 使用 jackson序列格式化日期
- asp代码写的,微信会员报名转发分享带上下级和邀约人关系并且能微信支付asp编号的
- Python学习心得--变量类型篇
- linux ubuntu 学习总结(day01)基本命令学习
- sourcetree的安装及使用
- 160301、js倒计时,页面上显示时间
- redis rdb文件解析
热门文章
- [BZOJ4542] [JZYZOJ2014][Hnoi2016] 大数(莫队+离散化)
- 【欧拉函数】BZOJ4173-数学
- Codeforces Beta Round #92 (Div. 1 Only) A. Prime Permutation 暴力
- linux基础命令学习(四)用户与群组
- 面试&;笔试---c语言之字符串处理
- undefined null 各种值比较(面试题)
- PHP格式化金钱函数
- Out of memory: Kill process 内存不足
- JS中实现字符串和数组的相互转化
- cocos2d-x:将iOS项目编译成Andriod项目