一.先上基础知识(出处不详):
![](https://img-blog.csdnimg.cn/img_convert/623ed78d59d67a7bc8bd7c900d4ef964.png)
二.工厂模式解决什么问题?
答:要创建一个对象,但是创建过程很复杂,不想在业务代码中暴露创建逻辑,只想直接使用这个对象。那么,这种创建对象的方式就用到了工厂模式。
三.我项目中用到的工厂方法模式。
场景:在基于SpringCloud的微服务项目中,使用Feign调用其他服务暴露的接口,调用失败后的回调方法用到了工厂模式。例如,在审批服务中调用了用户信息服务,来获取某个用户的邮箱信息。
用户服务暴露接口"remoteUserService":fallbackFactory = RemoteUserFallbackFactory.class定义了失败回调RemoteUserFallbackFactory这个类
@FeignClient(contextId = "remoteUserService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteUserFallbackFactory.class)
public interface RemoteUserService
{
/**
* 通过用户名查询用户信息
*
* @param username 用户名
* @param source 请求来源
* @return 结果
*/
@GetMapping("/user/info/{username}")
public R<LoginUser> getUserInfo(@PathVariable("username") String username, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
}
抽象工厂接口:org.springframework.cloud.openfeign.FallbackFactory
public interface FallbackFactory<T> {
T create(Throwable cause);
public static final class Default<T> implements FallbackFactory<T> {
final Log logger;
final T constant;
public Default(T constant) {
this(constant, LogFactory.getLog(Default.class));
}
Default(T constant, Log logger) {
this.constant = Util.checkNotNull(constant, "fallback", new Object[0]);
this.logger = (Log)Util.checkNotNull(logger, "logger", new Object[0]);
}
public T create(Throwable cause) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("fallback due to: " + cause.getMessage(), cause);
}
return this.constant;
}
public String toString() {
return this.constant.toString();
}
}
}
具体工厂:RemoteUserFallbackFactory
@Component
public class RemoteUserFallbackFactory implements FallbackFactory<RemoteUserService>
{
private static final Logger log = LoggerFactory.getLogger(RemoteUserFallbackFactory.class);
@Override
public RemoteUserService create(Throwable throwable) {
log.error("用户服务调用失败:{}", throwable.getMessage());
return new RemoteUserService() {
@Override
public R<LoginUser> getUserInfo(String username, String source) {
return R.fail("获取用户失败:" + throwable.getMessage());
}
};
}
业务代码中的应用:
@Autowired
private RemoteUserService remoteUserService;
R<LoginUser> userInfo = remoteUserService.getUserInfoByUserId(member.getUserId(), SecurityConstants.INNER);
SysUser sysUser = userInfo.getData().getSysUser();
userEmails.add(sysUser.getEmail());
四.解析:
抽象工厂只是定义了一个创建对象的接口,对象的创建放在子类去实现。如果新增其他服务的回调,只需要像RemoteUserFallbackFactory一样,实现FallbackFactory接口就可以了。
五.抽象工厂模式
什么是抽象工厂模式?与工厂方法模式有什么区别?
答:在以上的例子中,使用的是工厂方法模式,通过创建不同的具体工厂来创建某个特定的对象,如创建RemoteUserService对象用的是创建RemoteUserFallbackFactory这个具体工厂。那么,创建RemoteRoleService对象就要创建RemoteRoleFallbackFactory这个具体工厂。。。以此类推。
抽象工厂模式是对工厂方法模式的进一步深化,可以实现让一个工厂负责创建多个不同类型的对象。
2.引用一个抽象工厂的例子(引用:https://baijiahao.baidu.com/s?id=1744096525180947851&wfr=spider&for=pc)
以典型的跨端场景为例,用户可购买会员有多种类型,每种类型的会员在iOS、Android、PC下权益页稍有不同,并且实例化过程十分复杂。如果不用工厂模式,就需要在每处需要实例的地方,去编写复杂的实例化代码,当实例化过程发生修改,也需要每处修改,维护成本非常高。如果用简单工厂模式或者工厂方法模式,不用抽象工厂模式,就需要每个类型会员实现三个工厂,也不易于维护。
在这个场景下,我们可以用抽象工厂模式解决,编写抽象工厂、会员抽象类,并实现iOS、Android、PC三个具体工厂,根据场景选取需要的具体工厂获取会员实例。
/抽象产品
public interface Vip {}
//具体产品
public class NormalVip implements Vip {} //普通会员
public class MonthlyVip implements Vip {} //包月会员
public class IOSNormalVip extends NormalVip {}
public class AndroidNormalVip extends NormalVip {}
public class PCNormalVip extends NormalVip {}
public class IOSMonthlyVip extends MonthlyVip {}
public class AndroidMonthlyVip extends MonthlyVip {}
public class PCMonthlyVip extends MonthlyVip {}
//抽象工厂
public interface AbstractVipFactory {
Vip createNormalVip();
Vip createMonthlyVip();
}
//具体工厂
public class IOSVipFactory implements AbstractVipFactory {
@Override
public Vip createNormalVip() {
return new IOSNormalVip();
}
@Override
public Vip createMonthlyVip() {
return new IOSMonthlyVip();
}
}
...
//调用示例
public class Client {
public static void main(String[] args) {
IOSVipFactory iosVipFactory = new IOSVipFactory();
Vip iosNormalVip = iosVipFactory.createNormalVip();
}
}