package com.leitao.demo.design;
/**
* 享元模式
* @Description: TODO
* @Author LeiTao
* @Date 2023/5/2
* @Version V1.0
**/
public class Flyweight {
public static void main(String[] args) {
PieceFactory pieceFactory = new PieceFactory();
Piece piece1 = pieceFactory.getPiece(0);
Piece piece2 = pieceFactory.getPiece(0);
Piece piece3 = pieceFactory.getPiece(0);
System.out.println(piece1);
System.out.println(piece2);
System.out.println(piece3);
piece1.draw(23,45);
}
}
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 = "白色";
}
@Override
public void draw(int x, int y) {
System.out.println("画了一个" + color + "颜色的棋子,坐标为X:" + x + " Y:" + y);
}
}
class BlackPiece extends Piece{
public BlackPiece() {
this.color = "黑色";
}
@Override
public void draw(int x, int y) {
System.out.println("画了一个" + color + "颜色的棋子,坐标为X:" + x + " Y:" + y);
}
}
package com.leitao.demo.design;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* @Description: TODO
* @Author LeiTao
* @Date 2023/5/2
* @Version V1.0
**/
public class FlyweightPattern {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Random random = new Random();
String[] colors = {"红色","蓝色","紫色","绿色","黑色"};
for (int i = 0; i <= 10; i++) {
int x = random.nextInt(colors.length);
Shape shape = shapeFactory.getShape(colors[x]);
System.out.print("第" + i + "个圆");
shape.draw(random.nextInt(2023),random.nextInt(1128));
}
}
}
class ShapeFactory{
private Map<String,Shape> map = new HashMap<>();
public Shape getShape(String key){
if (!map.containsKey(key)){
map.put(key, new Circle(key));
System.out.println("创建了一个颜色为:" + key + "的圆");
}
return map.get(key);
}
}
abstract class Shape{
protected String Color;
public abstract void draw(int x, int y);
}
class Circle extends Shape {
public Circle(String color) {
this.Color = color;
}
@Override
public void draw(int x, int y) {
System.out.println("画了一个圆,颜色为:" + Color + "坐标为X为:" + x + " Y为:" + y);
}
}