added flyweight example

This commit is contained in:
Louis Heredero 2024-11-04 11:35:09 +01:00
parent dfd4dba1d7
commit f37a8cd665
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
5 changed files with 100 additions and 0 deletions

View File

@ -0,0 +1,15 @@
package learn.simple_flyweight;
public class ConcreteFlyweight extends Flyweight {
private long intrinsicState;
public ConcreteFlyweight(long intrinsicState) {
super();
this.intrinsicState = intrinsicState;
}
@Override
public void operation(long extrinsicState) {
System.out.println("Flyweight " + intrinsicState + " calling operation with extrinsic state " + extrinsicState);
}
}

View File

@ -0,0 +1,13 @@
package learn.simple_flyweight;
import java.util.Arrays;
public abstract class Flyweight {
private long[] internalStorage = new long[1000000];
public Flyweight() {
Arrays.fill(internalStorage, 1);
}
public abstract void operation(long extrinsicState);
}

View File

@ -0,0 +1,17 @@
package learn.simple_flyweight;
import java.util.HashMap;
import java.util.Map;
public class FlyweightFactory {
private static final Map<Integer, Flyweight> flyweights = new HashMap<>();
public Flyweight getFlyweight(Integer key) {
Flyweight flyweight = flyweights.get(key);
if (flyweight == null) {
flyweight = new ConcreteFlyweight(key);
flyweights.put(key, flyweight);
}
return flyweight;
}
}

View File

@ -0,0 +1,40 @@
package learn.simple_flyweight;
import java.util.Random;
public class Main {
private static final Random rand = new Random();
public static void main(String[] args) {
int rounds = 100;
debugMemory();
testFlyweight(rounds);
debugMemory();
testUnsharedFlyweight(rounds);
debugMemory();
}
private static void debugMemory() {
long totalMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
long usedMemory = totalMemory - freeMemory;
System.out.printf("Memory: %d%n", usedMemory);
}
private static void testFlyweight(int rounds) {
FlyweightFactory factory = new FlyweightFactory();
for (int i = 0; i < rounds; i++) {
Flyweight flyweight = factory.getFlyweight(rand.nextInt(10));
flyweight.operation(i);
}
}
private static void testUnsharedFlyweight(int rounds) {
for (int i = 0; i < rounds; i++) {
Flyweight flyweight = new UnsharedConcreteFlyweight(rand.nextInt(10));
flyweight.operation(i);
}
}
}

View File

@ -0,0 +1,15 @@
package learn.simple_flyweight;
public class UnsharedConcreteFlyweight extends Flyweight {
private long allState;
public UnsharedConcreteFlyweight(long allState) {
super();
this.allState = allState;
}
@Override
public void operation(long extrinsicState) {
System.out.println("Unshared Flyweight " + allState + " calling operation with extrinsic state " + extrinsicState);
}
}