隐藏页面特效

设计模式--享元模式

类图

 

 

源码

package weight; /** * 坐标类:外部状态类 * @author fly * */ class Coordinates { private int x; private int y; public Coordinates(int x,int y) { // TODO Auto-generated constructor stub this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } 2) 抽象享元类 package weight; /** * 围棋棋子类:抽象享元类 * @author fly * */ abstract class IgoChessman { public abstract String getColor(); public void locate(Coordinates coord){ System.out.println("棋子颜色:"+this.getColor()+",棋子位置:"+coord.getX()+","+coord.getY()); } } /** * 黑色棋子类:具体享元类 * @author fly * */ class BlackIgoChessman extends IgoChessman{ @Override public String getColor() { // TODO Auto-generated method stub return "黑色"; } } /** * 白色棋子类:具体享元类 * @author fly * */ class WhiteIgoChessman extends IgoChessman{ @Override public String getColor() { // TODO Auto-generated method stub return "白色"; } } 3) 享元工厂类 package weight; import java.util.Hashtable; /** * 围棋棋子工厂类:享元工厂类 * @author fly * */ public class IgoChessmanFactory { private static IgoChessmanFactory instance = new IgoChessmanFactory(); private static Hashtable ht; public IgoChessmanFactory() { // TODO Auto-generated constructor stub ht = new Hashtable(); IgoChessman black,white; black = new BlackIgoChessman(); ht.put("b", black); white = new WhiteIgoChessman(); ht.put("w", white); } public static IgoChessmanFactory getInstance(){ return instance; } public static IgoChessman getIgoChessman(String color){ return (IgoChessman)ht.get(color); } } 4) 测试类 package weight; /** * 客户端测试类 * @author fly * */ public class Client { public static void main(String[] args) { IgoChessman black1,black2,black3,white1,white2; IgoChessmanFactory factory; factory = IgoChessmanFactory.getInstance(); black1 = factory.getIgoChessman("b"); black2 = factory.getIgoChessman("b"); black3 = factory.getIgoChessman("b"); System.out.println("判断两颗黑棋是否相同:"+(black1==black2)); white1 = factory.getIgoChessman("w"); white2 = factory.getIgoChessman("w"); System.out.println("判断两颗白棋是否相同:"+(white1==white2)); black1.locate(new Coordinates(1, 2)); black2.locate(new Coordinates(3, 4)); black3.locate(new Coordinates(1, 3)); white1.locate(new Coordinates(2, 5)); white2.locate(new Coordinates(2, 4)); } }

 

 

测试截图

 

 


__EOF__

本文作者往心。
本文链接https://www.cnblogs.com/lx06/p/15688465.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   往心。  阅读(25)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
历史上的今天:
2020-12-14 jsp标签问题
点击右上角即可分享
微信分享提示