//Extrinsic.java
package com.demo;
public interface Extrinsic {
String getDivision();
}
Fly
Weight Design Pattern
package com.demo;
public interface Extrinsic {
String getDivision();
}
//ExtrinsicFactory.java
package com.demo;
import java.util.*;
public class ExtrinsicFactory {
public static Map<String, Extrinsic>m=new HashMap<String,Extrinsic>();
public static int count;
//static factorymethod that gives Extrinsic object by checking buffer/cache(m)
public static Extrinsic getExtrinsic(String division)
{
//here Fly Weight logic is implementing
if(m.containsKey(division))
{
Object o=m.get(division);
Extrinsic i=(Extrinsic)o;
return(i);
}
Extrinsic extr=new ExtrinsicFactory.ExtrinsicClass(division);
m.put(division,extr);
return(extr);
}//end of factory method
//inner class acting as Extrinsic class having logic to hold division
public static class ExtrinsicClass implements Extrinsic
{
private String division;
private ExtrinsicClass(String division)
{
this.division=division;
count++;
System.out.println("no.of Extrinsic object="+count);
}
public String getDivision()
{
return(division);
}
}//End of Extrinsic class
}//end of ExtrinsicFactory class
//ICard.java
package com.demo;
public class ICard
{
//Intrinsic properties
private String empname;
private int empid;
//Extrinsic properties
private Extrinsic extr;
public ICard(String empname, int empid, Extrinsic extr)
{
this.empname=empname;
this.empid=empid;
this.extr=extr;
}
public void print()
{
System.out.println("Emp name :"+empname);
System.out.println("Emp id :"+empid);
System.out.println("Division :"+extr.getDivision());
}
}
//MainApp.java
package com.demo;
public class MainApp {
public static void main(String args[])
{
ICard ic1=new ICard("raj",111,ExtrinsicFactory.getExtrinsic("A"));
ICard ic2=new ICard("RAVI",222,ExtrinsicFactory.getExtrinsic("A"));
ICard ic3=new ICard("RAMESH",666,ExtrinsicFactory.getExtrinsic("B"));
ICard ic4=new ICard("RAMANA",999,ExtrinsicFactory.getExtrinsic("A"));
System.out.println("------------");
ic1.print();
System.out.println("------------");
ic2.print();
System.out.println("------------");
ic3.print();
System.out.println("------------");
ic4.print();
}
}
/*
* output:
* no.of Extrinsic object=1
no.of Extrinsic object=2
------------
Emp name :raj
Emp id :111
Division :A
------------
Emp name :RAVI
Emp id :222
Division :A
------------
Emp name :RAMESH
Emp id :666
Division :B
------------
Emp name :RAMANA
Emp id :999
Division :A
*/
This Buffer or cache development have Extrinsic Data is nothing but implementation of private Design pattern
No comments:
Post a Comment