工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象,用工厂方法代替new操作的一种模式
工厂模式
定义一个用于创建对象的接口,让子类决定将哪一个类实例化。工厂模式让一个类的实例化延迟到其子类。工厂模式又称为工厂方法模式,又可称为虚拟构造器模式或多态工厂模式。工厂模式是一种类创建型模式
var Dialog = function(){
this.show = function(){
console.log(this.name + ' is show -> ' + this.element);
}
};
Dialog.createNotice = function(){
var _dialog = new Dialog();
_dialog.element = '<div>notice</div>';
_dialog.name = 'notice';
return _dialog;
};
Dialog.createToast = function(){
var _dialog = new Dialog();
_dialog.element = '<div>toast</div>';
_dialog.name = 'toast';
return _dialog;
};
Dialog.createWarnin = function(){
var _dialog = new Dialog();
_dialog.element = '<div>warnin</div>';
_dialog.name = 'warnin';
return _dialog;
};
var Factory = {};
Factory.NoticeFactory = function(){
return Dialog.createNotice();
}
Factory.ToastFactory = function(){
return Dialog.createToast();
}
Factory.WarninFactory = function(){
return Dialog.createWarnin();
}
var notice = Factory.NoticeFactory();
var toast = Factory.ToastFactory();
var warnin = Factory.WarninFactory();
notice.show(); //notice is show -> <div>notice</div>
toast.show(); //toast is show -> <div>toast</div>
warnin.show(); //warnin is show -> <div>warnin</div>
与简单工厂的区别就是将类的所有实现方法进行拆分
简单工厂模式
https://blog.csdn.net/Hi_xiexialing/article/details/56665083
抽象工厂
推荐阅读:
https://blog.csdn.net/u012156116/article/details/80857255
https://segmentfault.com/a/1190000012422198
网友评论