js面向对象之继承学习 模拟策略模式
function CacheStrategy(){
this.getCache = function(CacheService){alert("cacheStrategy getCache function!");};
this.reloadCache = function(CacheService){alert("cacheStrategy reloadCache function!");};
}
function MemCache(){
this.getCache = function(CacheService){
/**
缓存数据
**/
alert(CacheService.getData());
alert("memCache getCache function!");
};
this.reloadCache=function(CacheService){
alert("memCache reloadCache function!");
}
}
MemCache.prototype = new CacheStrategy();
function OsCache(){
this.getCache = function(CacheService){
/**
缓存数据
**/
alert(CacheService.getData());
alert("osCache getCache function!");
};
this.reloadCache=function(CacheService){
alert("OsCache reloadCache function!");
}
}
OsCache.prototype = new CacheStrategy();
function CacheService(){
this.getCache = function(CacheStrategy){};
this.getData = function(){alert("cacheService getData function !");};
this.getCacheKey = function(){};
this.useCache = function(){};
this.reloadCache = function(){};
}
function AbstractCache(){
this.cacheKey = this.autoCacheKey();
this.useCache = true;
this.cacheStrategy = new MemCache();
}
AbstractCache.prototype = new CacheService();
AbstractCache.prototype.autoCacheKey = function(){
return "123";
}
AbstractCache.prototype.setCacheKey = function(_cacheKey){
this.cacheKey = _cacheKey;
}
AbstractCache.prototype.getCacheKey = function(){
return this.cacheKey;
}
AbstractCache.prototype.setUseCache = function(_useCache){
this.useCache = _useCache;
}
AbstractCache.prototype.getUseCache = function(){
return this.useCache;
}
AbstractCache.prototype.setCacheStrategy = function(_cacheStrategy){
this.cacheStrategy = _cacheStrategy;
}
AbstractCache.prototype.getCache = function(){
return this.cacheStrategy.getCache(this);
}
AbstractCache.prototype.reloadCache = function(){
return this.cacheStrategy.reloadCache(this);
}
function ResourceCache(){
}
ResourceCache.prototype = new AbstractCache();
ResourceCache.prototype.getData = function(){
return "data:11111111111111111111";
}
html测试页面
<html>
<head>
<script type="text/javascript" src="classtest.js" ></script>
<title>js类测试</title>
</head>
<script>
var abstractCache = new ResourceCache();
//abstractCache.setCacheStrategy(new OsCache());
abstractCache.getCache();
abstractCache.setCacheKey(456);
alert(abstractCache.getCacheKey());
</script>
<body>
</body>
</html>
本文通过具体示例讲解了JavaScript中面向对象的继承及策略模式的应用。定义了多个类来展示不同缓存策略的实现方式,包括内存缓存(MemCache)和操作系统缓存(OsCache),并演示了如何在抽象缓存类(AbstractCache)中应用这些策略。
576

被折叠的 条评论
为什么被折叠?



