import java.nio.channels.Pipe; public class 享元模式 { public static void main(String[] args) { pieceFactory factory=new pieceFactory(); Piece whitePiece=factory.getPiece(0); Piece whitePiece1=factory.getPiece(1); Piece whitePiece2=factory.getPiece(0); System.out.println(whitePiece); System.out.println(whitePiece); System.out.println(whitePiece);//位于同一位置 whitePiece.draw(25,30); } } class pieceFactory{ private Piece[] pieces={new whitePiece(),new blackPiece()}; public Piece getPiece(int key) { if(key==0) return pieces[0]; else return pieces[1]; } } abstract class Piece{ protected String color; public abstract void draw(int x,int y); } class whitePiece extends Piece{ public whitePiece() { this.color="white"; } @Override public void draw(int x,int y) { System.out.println("draw a color: "+color+"piece x: "+x+"piece y: "+y); } } class blackPiece extends Piece{ public blackPiece() { this.color="black"; } @Override public void draw(int x,int y) { System.out.println("draw a color: "+color+"piece x: "+x+"piece y: "+y); } }
运行结果
标签:享元,draw,设计模式,whitePiece,int,模式,color,Piece,public From: https://www.cnblogs.com/cinan/p/17798950.html