Thursday, May 22, 2014

Multiton Pattern (Registry of Singletons) in Java


Simple Note

From reference:
The multiton pattern expands on the singleton concept to manage a map of named instances as key-value pairs.
Rather than having a single instance per application (e.g. the java.lang.Runtime object in the Java programming language) the multiton pattern instead ensures a single instance per key.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/multiton

Run TestMain.java to test.

Put Vitamin into VitaminBox, there is only one VitaminBox for a kind of Vitamin.

Reference:

Multiton pattern

Wednesday, May 21, 2014

Smart Proxy Pattern in Java


Simple Note

From reference:
A smart proxy interposes additional actions when an object is accessed. Typical uses include:
Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer),
Loading a persistent object into memory when it's first referenced,
Checking that the real object is locked before it is accessed to ensure that no other object can change it.

Smart References: providing a sophisticated access to certain objects such as tracking the number of references to an object and denying access if a certain number is reached, as well as loading an object from database into memory on demand.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/smartproxy

Run TestMain.java to test.

OperatorProxy will limit the operation performed by RealOperator, at most 3 operation at a time.

Reference:

Proxy Design Pattern

Proxy Pattern

Protection Proxy Pattern in Java


Simple Note

(From Reference)
Protective Proxy – The protective proxy acts as an authorisation layer to verify if the actual user has access to appropriate content. An example can be thought about the proxy server which provides restrictive internet access in office. Only the websites and contents which are valid will be allowed and the remaining ones will be blocked.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/protectionproxy

Run TestMain.java to test.

ProxyMouseController will check role first then control mouse via RealMouseController

Reference:

Gang of Four – Proxy Design Pattern

Tuesday, May 20, 2014

Remote Proxy Pattern in Java


Simple Note

(From Reference)
Remote Proxy – A remote proxy can be thought about the stub in the RPC call. The remote proxy provides a local representation of the object which is present in the different address location. Another example can be providing interface for remote resources such as web service or REST resources.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/remoteproxy

Run TestMain.java to test.

Access Google Geo Services via GeoServiceProxy

The sample is based on Java Practice: java.net practice, Use Google Geocode Web Service

Reference:

Gang of Four – Proxy Design Pattern

Sunday, May 18, 2014

Control Mouse Move in Java


Simple Note

Use java.awt.Robot class.

Code

package proxy.remoteproxy;

import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Robot;

public class TestMain {
    public static void main (String args[]) throws AWTException, InterruptedException {
        // get X/Y position of mouse cursor
        int posX = (int)MouseInfo.getPointerInfo().getLocation().getX();
        int posY = (int)MouseInfo.getPointerInfo().getLocation().getY();

        Robot bot = new Robot();
        // move around a rect
        bot.mouseMove(posX-30, posY-30);
        Thread.sleep(1000);
        bot.mouseMove(posX+30, posY-30);
        Thread.sleep(1000);
        bot.mouseMove(posX+30, posY+30);
        Thread.sleep(1000);
        bot.mouseMove(posX-30, posY+30);
        Thread.sleep(1000);
        bot.mouseMove(posX-30, posY-30);
        Thread.sleep(1000);
        // back to start position
        bot.mouseMove(posX, posY);
    }
}


Reference

Class Robot

Get X/Y Position of Mouse Cursor in Java


Simple Note

Use java.awt.MouseInfo as below:

        MouseInfo.getPointerInfo().getLocation().getX();
        MouseInfo.getPointerInfo().getLocation().getY();

Reference

Get Mouse Position

Saturday, May 17, 2014

Virtual Proxy Pattern in Java


Simple Note

(From SO)
A Virtual Proxy creates expensive objects on demand

(From Wiki)
Lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/virtualproxy

Run TestMain.java to test.

ProxyFactorial will create and cache the Factorial object on demand.

Reference:

Proxy pattern

Lazy initialization

Great answer at SO

Factorial

Friday, May 16, 2014

Decorator Pattern in Java


Simple Note

(From wiki):
The decorator pattern (also known as Wrapper, an alternative naming shared with the Adapter pattern) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/decorator

Run TestMain.java to test.

OldSiren().alarm() will only output a message in console, BeepDecorator can wrap OldSiren to add a beep.

Reference:

Decorator pattern

Grate answer at stackoverflow

Thursday, May 15, 2014

Builder Pattern in Java


Simple Note

(From wiki):
the intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/builder

Run TestMain.java to test.

Add base rice and lots of ingredients one by one to DonburiBuilder then build Donburi.

Reference:

Builder pattern

Grate answer at stackoverflow

Donburi

Factory Method Pattern in Java


Simple Note

(From wiki):
The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/factory/factorymethod

Run TestMain.java to test.

abstract class Audience has a method enjoy, will get a Player to play something then enjoy.
the abstract method getPlayer can be overridden by subclass to provide different Player as needed.

Reference:

Factory method pattern (wiki)

Wednesday, May 14, 2014

Abstract Factory Pattern in Java


Simple Note

(From wiki):
The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.
(From OODesign)
Offers the interface for creating a family of related object, without explicitly specifying their classes.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/factory/abstractfactory

Run TestMain.java to test.

A FoodStore  that sells Bread from BreadFactory in odd weeks and sells PASTA from PastaFactory in even weeks.

In my opinion, Abstract Factory Pattern is most likely 'Chained Simple Factory Pattern'.

Reference:

Abstract factory pattern

Abstract Factory

Simple Factory Pattern in Java


Simple Note

Simple Factory Pattern:
A method that can return different hardcoded subtypes.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/factory/simplefactory

BreadFactory that produce WonderfulBread at 3rd day of a week and produce CommonBread in other days

Can rely on the abstract class "Bread" in program, do not need to know whether it is a WonderfulBread or CommonBread

Reference:

Factory (object-oriented programming)

Simple Factory vs. Factory Method vs. Abstract Factory

Saturday, May 10, 2014

JAVA Protected Modifier Testing


Simple Note

A little bit confused by protected modifier in JAVA:

Test cases:
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/Commons/src/modifier/protectedtest

see derived class in packagea/packageb.

References

Controlling Access to Members of a Class
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Sunday, May 4, 2014

JMX Getting Started: Standard MBean


Simple Note

Introduction

From official site:
The JMX technology provides the tools for building distributed, Web-based, modular and dynamic solutions for managing and monitoring devices, applications, and service-driven networks. By design, this standard is suitable for adapting legacy systems, implementing new management and monitoring solutions, and plugging into those of the future. 

This article describe how to write JMX Standard MBeans.

Result

View demo on line
http://screencast.com/t/R80hAMjZcggm

Program

Test.java
The testing class to run.

TestBean.java
Test java bean, contains some operations and attribute.

TestBeanMBean.java
The interface for TestBean, according to JMX Standard MBean convention the name should be TestBeanMBean.

How to Run (Windows7/JDK6)

1. Download the bin/test  folder to some where.

2. Open cmd, go to the folder that contains the downloaded test folder.

3. Run it with "java -cp . test.Test".

4. Open jconsole.exe at your jdk/bin folder and try it.

Note:
1. If you didn't setup PATH properly (i.e. cannot execute java command any where) you can copy test folder to path_to_your_jdk_folder/bin.

2. You may need to change TMP folder to different location, please refer to the related thread on oracle community.

Reference

Standard MBean
http://docs.oracle.com/javase/tutorial/jmx/mbeans/standard.html

TMP Issue
https://community.oracle.com/thread/1176284?start=0&tstart=0

Download

Full project at github
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/JMX/MBeans/StandardMBean