android 中的工厂模式,Android 与 设计模式(2)——工厂模式

Android 与 设计模式(2)——工厂模式

2020-08-18 07:02

阅读数 42

工厂模式

不会对使用者暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

以简单工厂为例

// 提供统一的抽象接口供子类实现 public interface Factory { void create(); } // 子类实现抽象接口

public class Computer implements Factory{ @Override public void create() {

System.out.println("I am Computer Product ! Create an Computer"); } } public

class Car implements Factory{ @Override public void create() {

System.out.println("I am Car Product ! Create a car"); } } //真正的工厂方法,根据需求提供实例

public class RealFactory { public Factory getFactory (String want) { if (want ==

null || "".equals(want)) { return null; } if (want.equals("car")) { return new

Car(); }else if (want.equals("computer")) { return new Computer(); } else {

return null; } } } //使用实例 public class FactoryDemo { public static void main

(String[] args) {/** * 定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method

使一个类的实例化延迟到其子类。 */ RealFactory factory = new RealFactory(); Factory carFactory

= factory.getFactory("car"); carFactory.create(); Factory computerFactory =

factory.getFactory("computer"); computerFactory.create(); } }

Android 中的工厂模式

优秀实现

用于使用多种第三方的中间层,根据配置调用真正的实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值