" + sharedData);
}
}
public class FlyweightFactory {
private Map
public Flyweight getFlyweight(String key) {
if (flyweights.containsKey(key)) {
return flyweights.get(key);
} else {
Flyweight flyweight = new ConcreteFlyweight(key);
flyweights.put(key, flyweight);
return flyweight;
}
}
}
public class Client {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
Flyweight flyweight1 = factory.getFlyweight(\"data1\");
flyweight1.operation();
Flyweight flyweight2 = factory.getFlyweight(\"data2\");
flyweight2.operation();
Flyweight flyweight3 = factory.getFlyweight(\"data1\");
flyweight3.operation();
}
}
在上述示例中,我们创建了一个享元接口(Flyweight)和具体的享元类(ConcreteFlyweight)。享元工厂类(FlyweightFactory)用于管理和创建享元对象。在客户端代码中,我们通过享元工厂类获取共享对象,并使用共享对象的方法。在这个例子中,我们共享了字符串对象,通过共享减少了内存消耗。
### 示例说明2:共享图形对象
```java
public interface Shape {
void draw();
}
public class Circle implements Shape {
private String color;
public Circle(String color) {
this.color = color;
}
public void draw() {
System.out.println(\"Drawing a circle with color: \" + color);
}
}
public class ShapeFactory {
private Map<String, Shape> shapes = new HashMap<>();
public Shape getShape(String color) {
if (shapes.containsKey(color)) {
return shapes.get(color);
} else {
Shape shape = new Circle(color);
shapes.put(color, shape);
return shape;
}
}
}
public class Client {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Shape redCircle = factory.getShape(\"red\");
redCircle.draw();
Shape blueCircle = factory.getShape(\"blue\");
blueCircle.draw();
Shape redCircle2 = factory.getShape(\"red\");
redCircle2.draw();
}
}
在上述示例中,我们创建了一个图形接口(Shape)和具体的图形类(Circle)。图形工厂类(ShapeFactory)用于管理和创建图形对象。在客户端代码中,我们通过图形工厂类获取共享对象,并使用共享对象的方法。在这个例子中,我们共享了颜色相同的圆形对象,通过共享减少了内存消耗。
通过以上示例,我们可以看到享元设计模式的优势,它可以大大减少对象的创建和内存消耗,提高性能和效率。
以上是关于Java享元设计模式优化对象创建提高性能和效率的完整攻略。根据具体情况,您可以根据示例代码进行定制和优化。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java享元设计模式优化对象创建提高性能和效率 - Python技术站