工厂模式:就是提供一个实例化对象的接口,让子类去决定实现哪个具体对象

1:简单工厂

public abstract class Person {

}
public class XiaoLi extends Person {
public void eat() {
System.out.println("小李吃饭");
}
}
public class XiaoMing extends Person {
public void eat() {
System.out.println("小明吃饭");
}
}
/**
* 简单工厂
*/
public class SimpleFactory {
public Person instance(String username) {
if (username.equals("1")) {
return new XiaoMing();
} else if (username.equals("2")) {
return new XiaoLi();
}
return null;
}
}
public class SimpleTest {
public static void main(String[] args) {
SimpleFactory factory = new SimpleFactory();
Person xiaoming = factory.instance("1");
Person xiaoli = factory.instance("2");
XiaoLi m = (XiaoLi) xiaoli;
m.eat();
XiaoMing l = (XiaoMing) xiaoming;
l.eat(); }
}
--------------------------------------------------------------------------------------------------------
2:抽象工厂
public abstract class Product {
}
public class MobilePhone extends Product {
public void desc() {
System.out.println("this is mobilephone");
}
}
public class Pen extends Product {
public void desc(){
System.out.println("this is pen");
}
}
/**
* 抽象工厂-每个类别创建自己的工厂
*/
public abstract class Afactory {
public abstract Product instance();
}
public class MobilePhoneFactory extends  Afactory {
@Override
public Product instance() {
return new MobilePhone();
}
}
public class PenFactory extends Afactory {
@Override
public Product instance() {
return new Pen();
}
}
/**
* 抽象工厂模式测试
* 工厂模式:提供一个实例化对象的接口,让子类去决定实例那个具体对象
*/
public class TestAbs {
public static void main(String[] args) {
Afactory penFactory = new PenFactory();
Pen pen = (Pen) penFactory.instance();
pen.desc();
Afactory mobileFactory = new MobilePhoneFactory();
MobilePhone mobilePhone = (MobilePhone) mobileFactory.instance();
mobilePhone.desc();
}
}

最新文章

  1. 第24/24周 数据库维护(Database Maintenance)
  2. Android 中MyApplication
  3. php 二分查找
  4. android 百度地图定位功能实现
  5. pearl(二分查找,stl)
  6. 关于UIFont和计算字符串的高度和宽度
  7. VR虚拟现实技术在教育领域的前景展望
  8. ASP.NET Core 2.0 使用支付宝PC网站支付
  9. UltraEdit激活方法
  10. 分布式进阶(十二)Docker固定Container IP
  11. Android的内存分配与回收
  12. PHP信号管理
  13. [九省联考2018]秘密袭击coat
  14. mysql添加用户,授权,刷新权限
  15. 第三周博客之二---Oracle中的sql语句
  16. Foundry feats. MultiverseStudio
  17. noip第3课资料
  18. skynet inject address file.lua
  19. 利用委托机制处理.NET中的异常
  20. monkey测试入门1

热门文章

  1. 语法检查程序LanguageTool学习和使用笔记
  2. 大数据笔记(四)——操作HDFS
  3. EventBus和Otto第三方构架
  4. HDU 5073 Galaxy (数学)
  5. React-Native 之 GD (二十一)APP 打包
  6. percona-toolkit 工具介绍
  7. linux基本目录
  8. 树的基本概念以及java实现二叉树
  9. Powershell指令集_2
  10. UI自动化之三种等待