装饰者模式
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
var User = function(name) {
this.name = name;
this.say = function() {
log.add("User: " + this.name);
};
}
var DecoratedUser = function(user, street, city) {
this.user = user;
this.street = street;
this.city = city;
this.say = function() {
log.add("Decorated User: " + this.user.name + ", " +
this.street + ", " + this.city);
};
return this;
}
// logging helper
var log = (function() {
var log = "";
return {
add: function(msg) { log += msg + "\n"; },
show: function() { console.log(log); log = ""; }
}
})();
function run() {
var user = new User("Kelly");
user.say(); //User: Kelly
var decorated = new DecoratedUser(user, "Broadway", "New York");
decorated.say(); //Decorated User: Kelly, Broadway, New York
log.show();
}
run();class User {
constructor(name){
this.name = name;
this.classType = 'normal';
}
say(){
log.add("User: " + this.name+ "; classType:" + this.classType);
}
}
class UserVip extends User {
constructor(name){
super(name);
this.classType = 'VIP';
}
}
class UserDecorator {
constructor(user,street){
this.user = user;
this.street = street;
}
getStreet(){
return " Decorated User Street is: "+this.street
}
say(){
const user = this.user;
log.add("User: " + user.name+ "; classType:" + user.classType + this.getStreet());
}
}
class CaseUserDecorator extends UserDecorator{
constructor(user, street, city){
super(user, street);
this.city = city;
}
getCity(){
return " caseDecorated User City is: "+this.city
}
say(){
const user = this.user;
log.add("User: " + user.name+ "; classType:" + user.classType + this.getStreet() + '; ' + this.getCity());
}
}
// logging helper
var log = (function() {
var log = "";
return {
add: function(msg) { log += msg + "\n"; },
show: function() { console.log(log); log = ""; }
}
})();
function run() {
var user = new User("Mike");
user.say(); //User: Mike; classType:normal
var decoratedUser = new UserDecorator(user, "Broadway");
decoratedUser.say(); // User: Mike; classType:normal Decorated User Street is: Broadway
var userVip = new UserVip("Kelly");
userVip.say(); //User: Kelly; classType:VIP
var decoratedVipUser = new CaseUserDecorator(userVip, "Broadway", "New York");
decoratedVipUser.say(); // User: Kelly; classType:VIP Decorated User Street is: Broadway; caseDecorated User City is: New York
log.show();
}
run();