JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Flyweight Pattern
  • Flyweight is a software design pattern.
  • Make instances of classes on the fly to improve performance efficiently.
  • A flyweight is an object that minimizes memory use ,by sharing
    as much data as possible with other similar objects;
  • It is a way to use objects in large numbers when a simple repeated
    representation would use an unacceptable amount of memory.
  • The term comes from the boxing weight class with the same name.
Purpose
  • Use sharing to support large numbers of fine-grained objects efficiently.

Applications
  • An application uses a large number of objects.
  • Storage costs are high because of the sheer quantity of objects.
  • Most object state can be made extrinsic.
  • Many groups of objects may be replaced by relatively few shared objects once
    extrinsic state is removed.
  • The application doesn't depend on object identity. Since flyweight objects may
    be shared, identity tests will return true for conceptually distinct objects.
Non-software examples of Flyweight  patterns

  • The Flyweight uses sharing to support large numbers of objects efficiently. 
  • The public switched telephone network is an example of a Flyweight. 
  • There are several resources such as dial tone generators, ringing generators, and digit
    receivers that must be shared between all subscribers.
  •  A subscriber is unaware of how many resources are in the pool when he or
    she lifts the handset to make a call.
  •  All that matters to subscribers is that a dial tone is provided, digits are 
    received, and the call is completed

Example:-1


Admission.java
package com.flyweight;

public abstract class Admission

  public abstract void admitStudent
(
AdmissionContext admissionContext);
}


AdmissionContext.java
package com.flyweight;

public class AdmissionContext 

  int std;
  public AdmissionContext(int std)
  
    this.std = std;
  }
  public int getStd()
  {
    return std; 
  }
}

GeneralAdmission.java
package com.flyweight;

public class GeneralAdmission extends Admission

  String admissionType = null;
  public GeneralAdmission(String admissionType)
  {  
    this.admissionType = admissionType;
  }
  public String getAdmissionType()
  {  
    return admissionType; 
  }
  
  public void admitStudent(AdmissionContext admissionContext)
  {
    System.out.println("Admissions type =
 "
+admissionType+" for std "+admissionContext.getStd())
  }
}


GeneralAdmissionFactory.java
package com.flyweight;

public class GeneralAdmissionFactory 
{  
  GeneralAdmission[] admissions = new GeneralAdmission[10];
  int seats = 0;
  public GeneralAdmission getGeneralAdmission(String
admissionType
)
  {  
    if(seats > 0)
    {   
      for(int i=0;i<seats;i++)
      {
        if(admissionType.equals(admissions[i].
getAdmissionType
()))
        return admissions[i]
      }
    }
    admissions[seatsnew GeneralAdmission(
admissionType);
    return admissions[seats++]
  }
  
  public GeneralAdmission[] getAdmissions()
  {
    return admissions; 
  }
  
  public void setAdmissions(GeneralAdmission[]
 
admissions)
  {
    this.admissions = admissions; 
  }
  public int getSeats()
  {
    return seats; 
  }
  
  public void setSeats(int seats)
  {
    this.seats = seats; 
  }
}

FlightweightPatternDemo.java
package com.flyweight;

class FlightweightPatternDemo 

  static GeneralAdmission[] generalAdmissions =
new GeneralAdmission[20];
  static AdmissionContext[] admissionContexts =
new AdmissionContext[20];
  static int seatRequest = 0;
  static GeneralAdmissionFactory generalAdmissionFactory;
  static void apply(int std, String admissionType)
  {
    generalAdmissions[seatRequest= generalAdmissionFactory.
getGeneralAdmission
(admissionType);
    admissionContexts[seatRequest++new AdmissionContext(std);
  }
  public static void main(String[] args)
  {
    generalAdmissionFactory = new GeneralAdmissionFactory();
    apply(2,"General");
    apply(5,"VIP");
    for(int i = 0;i<seatRequest;i++)
    {
      generalAdmissions[i].admitStudent(admissionContexts[i]);
    }
    System.out.println("Total seat Requests = "+
generalAdmissionFactory.getSeats
());
  }
}

Output:-

Download Zip Code

Example:2

Student.java
package com.model;

public class Student {
  private String name;
  private int id;
  private int score;
  private double avgScore;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public int getScore() {
    return score;
  }
  public void setScore(int score) {
    this.score = score;
  }
  public double getAvgScore() {
    return avgScore;
  }
  public void setAvgScore(double avgScore) {
    this.avgScore = avgScore;
  }
  public Student(double avgScore) {
    super();
    this.avgScore = avgScore;
  }
  public double getStanding(){
    return (((double)score)/avgScore-1.0)*100.0;
  }
}

Test.java
package com.test;

import com.model.Student;

public class Test {
  public static void main(String arg[]){
    String names[] {"Ralph""Alice""Sam"};
    int ids[] {100110021003};
    int scores[] {455565};
    double total = 0;
    for (int loopIndex = 0; loopIndex < scores.length; loopIndex++){
    total += scores[loopIndex];
    }
    double averageScore = total / scores.length;
    Student student = new Student(averageScore);
    for (int loopIndex = 0; loopIndex < scores.length; loopIndex++){
      student.setName(names[loopIndex]);
      student.setId(ids[loopIndex]);
      student.setScore(scores[loopIndex]);
      System.out.println("Name: " + student.getName());
      System.out.println("Standing: " +
      Math.round(student.getStanding()));
      System.out.println("");
      }
  }
}
Output:-

Download Zip code

Example:-

Pizza.java
package factory.pizzas;

import java.util.ArrayList;

abstract public class Pizza {
  String name;
  String dough;
  String sauce;
  ArrayList toppings = new ArrayList();

  public String getName() {
    return name;
  }

  public void prepare() {
    System.out.println("Preparing " + name);
  }

  public void bake() {
    System.out.println("Baking " + name);
  }

  public void cut() {
    System.out.println("Cutting " + name);
  }

  public void box() {
    System.out.println("Boxing " + name);
  }

  public String toString() {
    // code to display pizza name and ingredients
    StringBuffer display = new StringBuffer();
    display.append("---- " + name + " ----\n");
    display.append(dough + "\n");
    display.append(sauce + "\n");
    for (int i = 0; i < toppings.size(); i++) {
      display.append((String )toppings.get(i"\n");
    }
    return display.toString();
  }
}


CheesePizza.java
package factory.pizzas;

public class CheesePizza extends Pizza {
  public CheesePizza() {
    name = "Cheese Pizza";
    dough = "Regular Crust";
    sauce = "Marinara Pizza Sauce";
    toppings.add("Fresh Mozzarella");
    toppings.add("Parmesan");
  }
}

ClamPizza.java
package factory.pizzas;

public class ClamPizza extends Pizza {
  public ClamPizza() {
    name = "Clam Pizza";
    dough = "Thin crust";
    sauce = "White garlic sauce";
    toppings.add("Clams");
    toppings.add("Grated parmesan cheese");
  }
}


PepperoniPizza.java
package factory.pizzas;

public class PepperoniPizza extends Pizza {
  public PepperoniPizza() {
    name = "Pepperoni Pizza";
    dough = "Crust";
    sauce = "Marinara sauce";
    toppings.add("Sliced Pepperoni");
    toppings.add("Sliced Onion");
    toppings.add("Grated parmesan cheese");
  }
}

PizzaStore.java
package factory.pizzas;

public class PizzaStore {
  SimplePizzaFactory factory;
 
  public PizzaStore(SimplePizzaFactory factory) { 
    this.factory = factory;
  }
 
  public Pizza orderPizza(String type) {
    Pizza pizza;
 
    pizza = factory.createPizza(type);
 
    pizza.prepare();
    pizza.bake();
    pizza.cut();
    pizza.box();

    return pizza;
  }

}

SimplePizzaFactory.java
package factory.pizzas;

public class SimplePizzaFactory {

  public Pizza createPizza(String type) {
    Pizza pizza = null;

    if (type.equals("cheese")) {
      pizza = new CheesePizza();
    else if (type.equals("pepperoni")) {
      pizza = new PepperoniPizza();
    else if (type.equals("clam")) {
      pizza = new ClamPizza();
    else if (type.equals("veggie")) {
      pizza = new VeggiePizza();
    }
    return pizza;
  }
}

VeggiePizza.java
package factory.pizzas;

public class VeggiePizza extends Pizza {
  public VeggiePizza() {
    name = "Veggie Pizza";
    dough = "Crust";
    sauce = "Marinara sauce";
    toppings.add("Shredded mozzarella");
    toppings.add("Grated parmesan");
    toppings.add("Diced onion");
    toppings.add("Sliced mushrooms");
    toppings.add("Sliced red pepper");
    toppings.add("Sliced black olives");
  }
}

PizzaTestDrive.java
package factory.pizzas;

public class PizzaTestDrive {
 
  public static void main(String[] args) {
    SimplePizzaFactory factory =
new SimplePizzaFactory();
    PizzaStore store = new PizzaStore(factory);

    Pizza pizza = store.orderPizza("cheese");
    System.out.println("We ordered a " +
 pizza.getName
() "\n");
 
    pizza = store.orderPizza("veggie");
    System.out.println("We ordered a " +
 pizza.getName
() "\n");
  }
}

Output:-


Download Zip Code