A Story on Flyweight pattern

The Flyweight pattern
Flyweight Pattern

Swastika wants to introduce Theme in her blog but she is facing a problem.

The Problem:

Her blog is a combination of multiple widgets like Header widget, Footer Widget, Content Widget, Follower widget etc.

And those widgets are populated by backend call or any web service call in a simple term to load widget repetitively considered as a costly operation.

But as Swastika wants to introduce Theme, Theme can reorder the widget position as well as the color of the widgets, As Look and Feel are different for the different theme.

So the question pop up in Swastika’s mind is

Every time User changes the Theme should she reload the widget and populate the data?
Then it is a very bad design as it will load all costly widgets again and again so sluggish the response.

As Theme Change operation is in User's hand so Swastika can’t say users to “don’t change Theme frequently”. It will hurt her blog reputation.

So what she do now?

Swastika goes to her OOP Teacher for a Solution.

Sir Tell her to Reuse Widget but she believes her widget is stateful, so she explain the problem she has having now,

Swastika : Sir, I can use cache and put the Widget against a key in the cache and reuse it, but say my default theme is Classic Blue so every widget has color blue and say in classic Blue theme my Follower widget is in Left of the Screen.  Now if a user changes it to Slick green, then every widget must have to change their color to Green and say in Slick green theme, Follower widget will be on the Right side of the screen.

Now If I want to reuse my widget from cache it has Blue color and Follower widget position is in left so How I can reuse them without populating a new widget?


Sir: Wow, what a thought Swastika, very good but think about the scenario here your Widget populate data from backend and loaded once, But if you want to load it again for just to assign a color and position then you welcoming a potential danger to your blog.



So your new feature is not an addition it is a technical debt. Then it is better not to have it.

Think in an OOPs perspective when you change the Theme what happens, it just reorders your widget position and changes the color but widgets content are remain same. So if you load the Widget once and make your widget to capable of taking color and position value from outside then can you reuse your widget?

The answer is Yes as because apart from color and position your widget is state-independent in this context as it’s content does not change.

By Oops you can easily pass any attribute from outside and based on the theme your widget layout manager can decide what would be the position and color of your widget.



Flyweight pattern does the same.

What is a Flyweight pattern?

According to Wiki:
A flyweight is an object that minimizes memory usage 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. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.


So According to the definition widgets are Flyweight objects and reloading them unnecessary increase response time, So instead of that if we share color and position data to all Flyweight objects/Widgets then we can reuse the Widgets. And layoutManager computes the value of color and position by using Theme, An external data structure.

So every Flyweight object has two kinds of data

  1. Intrinsic data:  Which is State independent data, that is which does not change with the context like Swastika’s Widgets content does not change with the theme.
  2. Extrinsic Data:  Which is context-dependent data and changed with the context like Swastika’s Widgets color and position change with Theme.
To make our Flyweight object reusable we need to pass extrinsic data from outside to       Flyweight Object.

Coding Time:

Sir start the coding to show Swastika How he can make her widget reusable without loading it --help of Flyweight pattern.


IWidget.java

/**
*
*/
package com.example.flyweight;

/**
* @author Shamik Mitra
*
*/
public interface IWidget {
   
    public void setWidgetName(String name);
    public String getWidgetName();
    public void setWidgetContent(String content);   
    public void display();
    public void applyTheme(String color,String postion,Layoutmanager manager);

}



Now Sir create a layout manager and use Flyweight pattern there.

/**
*
*/
package com.example.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
* @author Shamik Mitra
*
*/
public class Layoutmanager {
   
    private static Layoutmanager mgr = new Layoutmanager();
   
    Map<String,IWidget> map = new HashMap<String,IWidget>();
   
    public static Layoutmanager get(){
        return mgr;
    }
   
    private Layoutmanager(){
        init();
    }
   
       
    public void addWidget(IWidget widget,String position){
        System.out.println("Adding Widget " + widget.getWidgetName()+  " in to position " + position);
       
    }
   
    private void init(){
       
        IWidget followerWidget = new IWidget(){
           
            private String name;
            private String content;
            private String color;
            private String position;

            @Override
            public void setWidgetName(String name) {
            this.name=name;
            }
           
            @Override
            public String getWidgetName() {
            return name;
            }

            @Override
            public void setWidgetContent(String content) {
            System.out.println("setting content first-time....loading from back end costly operation");
            this.content=content;
               
            }

            @Override
            public void display() {
                System.out.println(" Widget name : " + name);
                System.out.println(" Widget color : " + color);
                System.out.println(" Widget color : " + position);
                System.out.println(" Widget content : " + content);
            }

            @Override
            public void applyTheme(String color, String postion, Layoutmanager manager) {
                this.color=color;
                this.position=postion;
                manager.addWidget(this,postion);
               
            }
           
        };
       
        followerWidget.setWidgetName("Follower Widget");
        followerWidget.setWidgetContent("Showing blog Followers.");
        followerWidget.applyTheme("Blue", "LEFT", this);
        followerWidget.display();
        map.put(followerWidget.getWidgetName(), followerWidget);
       
       
       
    }
   
   
    public void ChangeTheme(){
        System.out.println("After Change Theme");
        for(String name : map.keySet()){
            if("Follower Widget".equalsIgnoreCase(name)){
                IWidget widget = map.get(name);
                widget.applyTheme("Green", "RIGHT", this);
                widget.display();
            }
        }
    }
   
    public static void main(String[] args) {
        Layoutmanager mgr = Layoutmanager.get();
        mgr.ChangeTheme();
    }
   
   

}







Explanation:
In Init() method sir creates Follower Widget for the first time and put it on a map so later on when the user does change the theme Sir can reuse the Widget.
Then apply the Classic Blue theme as the default theme.

When user call ChangeTheme() method, the application calls every Widget’s applyTheme() method and pass color and position from Layout manager so Widget/flyweights Object can change the color and set itself in the correct position.

Here Color and Position: the Extrinsic property of Flyweight Object.
Other properties of Widget is Intrinsic in nature.


Improvements:

Please note that this is a very basic example. To make it concrete more improvement needed like.

  1. The theme has to be a context Object implements an ITheme interface which dictates what will be color and other properties.
  2. LayOutManager should be the implementation of ILayoutManager interface as there can be various Layouts.
  3. The widget can be decorated by decorator pattern.
  4. We can segregate the logic of Widget creation and load it into the cache in a separate Class called WidgetFlyWeightFactory.












Learn Spring with Shamik

Spring Tutorial


After getting so many requests from my viewers and Students I am planning to Write Tutorials on Spring only for you.



And the good new is that I have published my Spring Tutorials with A4Academis which is an Academic site published quality Tutorials on various topics like C, C++, Java, Angular JS.



To read my Spring Tutorials please click the link below



About the Tutorials:

There are many Spring tutorials you can find on the web,  why you should read this tutorial?

When I am planning to write a Tutorials for Spring, I researched and found that most of the tutorials just covered the topics with just a few lines with basic examples and provide important Spring classes names in Tabular format, With not much details. Examples are unrealistic which is not

So , I thought it would be great if we write tutorial which try to teach you the core Spring with proper justification and example not only that I also try to point out the concepts which you need to know in very details as those are frequently used in IT world, SO after reading this tutorial you have a fair bit of idea and start using Spring in your Project !!!!


In the case of any clarification/queries drop a note on A4Academics or my personal blog.



Still,  If you want to learn more about Spring, Advance Spring I offer Tuition please contact me on
Shamik Mitra
9830471739(M)
mitrashamik@gmail.com



Happy reading!!!!!












Why should I write Getter/Setter?

Why should I write Getter/Setter?

When I started my career in Java, I was confused about getter and setter. One question always comes to my mind why should I write getter/setter? It looks weird kind of syntax to me.

I learned that by public access modifier one field of a class is accessible to any packages, and by Getter/setter what I am doing is same, make the field private and public the getter/setter method, so it can be accessed by any packages.

So, What is the difference between following two expressions?


public String name=”Shamik”;

Caller
========

String name = X.name;   //(X is a object instance);
X.name=”Shamik Mitra”;
private String name=”Shamik”;

public String getName(){
return name;}

public void setName(String name){
this.name=name;}

Caller
=====
String name = X.getname();
X.setName(“Shamik Mitra”);


confused.jpg
What the heck is getter/setter?




Slowly I realize why we use getter/setter & why it is important.

In this Article, I share that realization.

Realization :

The main difference of making a field public VS expose it through getter/setter is to hold the control to the property.If you make a field  public that means you provide direct access to the caller, caller can do anything with your filed knowingly/unknowingly say, caller can send a null value and if you use that filed in another method it may blow up that method by null pointer exception,

But If you provide getter/setter, you provide them an indirect access while taking full control, because the only way to set a value through setter and get a value through getter, So now you have exact one entry and one exit point of your field and getter/setters are methods!!! (Which allows block of codes) so you can do validation check on them and takes the decision you should set the caller value or not, same in getter method you can take decision should you return the actual reference or clone it and return the same to the caller.


So, getter/Setter are work as fuse or circuit breaker where the current has to be passed through fuse if anything goes abnormal fuse detached from the main circuit, so the circuit is safe. The concept is same here if anything goes wrong setter will not pass the value to class member field.

After reading the explanation, I know still you have one question

I understand all but generally, we do not write anything in getter/setter just return the field and set the field, which is same as exposing a field as public so why are you saying all of this?

To answer this question I say writing getter/setter we create a provision to add any validation method in future, currently, there is no validation but if anything goes wrong in future we just add validation logic in the setter.

But still, it creates a debate who are big follower of YAGNI(You aren't gonna need it),
they can say when there are no such validation constraints for a field why should I write getter/setter, I only expose it as public.

As per my understanding, The crux of YAGNI is to Unnecessary not make your code complex, As someone like to think big and try to make their code base so generic that it welcome any changes but most of the changes he/she thinks will never come.

Conclusion: The  getter/setter does not make your code complex and welcome future validations. So Please go for it blindly.