Thursday, February 7, 2013

social network security

  • www.ghostery.com

Ghostery looks for third party page elements (which we call "3pes") on the web pages you visit.
These can be things like social network plugins, advertisements, invisible pixels used for tracking and analytics, etc.
Ghostery notifies you that these things are present, and which companies operate them.
You can learn more about these companies, and if you wish, choose to block the 3pes they operate.


  • disconnect.me

nce installed on your Web browser, these extensions will tell you how many trackers they have blocked


  • www.secure.me

24/7 check of all posts
Protection from dangerous links and viruses
Monitoring of all photos, friends and activities



  • privacyfix.com

check your privacy settings across Facebook, Google and the other websites and companies collecting your data. Get to the fix with one click. Know when policies change.


  • simplewa.sh

It is called Simplewash, formerly Facewash, and it looks for profanity, references to drugs and other faux pas that you do not necessarily want, say, a law school admissions officer to se


  • socioclean.com

Socioclean is another application that scours your Facebook posts.

  • Social Network Analysis
Social network analysis [SNA] is the mapping and measuring of relationships and flows between people, groups, organizations, computers, URLs, and other connected information/knowledge entities. The nodes in the network are the people and groups while the links show relationships or flows between the nodes. SNA provides both a visual and a mathematical analysis of human relationships. Management consultants use this methodology with their business clients and call it Organizational Network Analysis [ONA].

http://www.orgnet.com/sna.html

  • Sentiment analysis uses
Sentiment analysis is extremely useful in social media monitoring as it allows us to gain an overview of the wider public opinion behind certain topics. Social media monitoring tools like Brandwatch Analytics make that process quicker and easier than ever before, thanks to real-time monitoring capabilities.
https://www.brandwatch.com/blog/understanding-sentiment-analysis/


  • Powerful social listening
Add context to the billions of conversations happening online every day. Brandwatch Analytics tells you more about the opinions, trends and people impacting your business.
https://www.brandwatch.com/brandwatch-analytics/?utm_expid=69193390-33.eKwp4nn8QDGu7MAr35s0Sg.0&utm_referrer=https%3A%2F%2Fwww.brandwatch.com%2Fblog%2Funderstanding-sentiment-analysis%2F

  • Sentiment analysis (sometimes known as opinion mining or emotion AI) refers to the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information. Sentiment analysis is widely applied to voice of the customer materials such as reviews and survey responses, online and social media
https://en.wikipedia.org/wiki/Sentiment_analysis

  • Basic Sentiment Analysis with Python
you can check out the code on Github
http://fjavieralba.com/basic-sentiment-analysis-with-python.html

  • This tutorial steps through a Natural Language API application using Python code. The purpose here is not to explain the Python client libraries, but to explain how to make calls to the Natural Language API. Applications in Java and Node.js are essentially similar. Consult the Natural Language API Samples for samples in other languages (including this sample within the tutorial).
https://cloud.google.com/natural-language/docs/sentiment-tutorial

  • Introduction to Sentiment Analysis Algorithms
Sentiment Analysis is the use of natural language processing, statistics, and text analysis to extract, and identify the sentiment of text into positive, negative, or neutral categories.
http://blog.algorithmia.com/introduction-sentiment-analysis-algorithms/

  • Sentiment analysis is also called opinion mining since it includes identifying consumer attitudes, emotions, and opinions of a company’s product, brand, or service.Sentiment Analysis is the use of natural language processing, statistics, and text analysis to extract, and identify the sentiment of text into positive, negative, or neutral categories.
http://blog.algorithmia.com/introduction-sentiment-analysis-algorithms/


  • Sentiment analytics involves the analysis of comments or words made by individuals to quantify the thoughts or feelings intended to be conveyed by words. Basically, it’s an attempt to understand the positive or negative feelings individuals have toward a brand, company, individual, or any other entity. In our experience, most of the sentiment collected around topics tends to be “neutral” (or convey no positive or negative feelings or meanings). It’s easiest to think about sentiment analytics when we look at Twitter data (or any other social site where people express a single thought or make a single statement). We can compute the sentiment of a document (such as a wiki post or blog entry) by looking at the overall scoring of sentiment words that it contains. For example, if a document contains 2,000 words that are considered negative versus 300 words that are considered positive in meaning, we may choose to classify that document as overall negative in sentiment. If the numbers are closer together (say 3,000 negative words versus 2,700 positive words or an almost equal distribution), we may choose to say that document is neutral in sentiment .The sentiment analysis being done by software is usually based on a sentiment dictionary for that language. The basic package comes with a predefined list of words that are considered as positive. Similarly, there is also a long list of words that can be considered negative. For many projects, the standard dictionary can be utilized for determining sentiment. In some special cases, you may have to modify the dictionary to include domain-specific positive and negative words. For example, the word Disaster can be a negative sentiment word in a majority of contexts, except when it is used to refer to a category of system such as “Disaster Recovery Systems.”
http://social-media-strategy-template.blogspot.com.tr/2016/04/sentiment-analysis-basics.html

  • sentiment analysis is the attempt to derive the emotion or 'feeling' of a body of text. The field of sentiment analysis and opinion mining usually also involves some form of data mining to get the text.
http://sentdex.com/sentiment-analysis/


  • Mining Twitter Data with Python (and JS) – Part 7: Geolocation and Interactive Maps
https://marcobonzanini.com/2015/06/16/mining-twitter-data-with-python-and-js-part-7-geolocation-and-interactive-maps/



  • The Social-Engineer Toolkit (SET) was created and written by the founder of TrustedSec. It is an open-source Python-driven tool aimed at penetration testing around Social-Engineering
https://www.trustedsec.com/social-engineer-toolkit/ 


  • What Is Website Cloaking?

A simple definition of the word cloaking is to conceal, hide or cause to be invisible. In the world of web design cloaking refers to showing different page content to regular users than what is shown to Google bot or other search engine crawlers.
Why is cloaking bad? Cloaking is frowned upon because it is a high risk violation of quality guidelines and accepted best practices for web page design. It also provides a level of deception as well as a bad user experience. The bad user experience is due to the search engine results not matching the actual page content. Also, in some cases cloaking is a method for transmitting malicious code to unsuspecting users.

https://impactsocialmedia.net/what-is-website-cloaking/


Wednesday, February 6, 2013

code sample question 1

int x = 10;  x += x--;  value of x?



x += x--;

This is equivalent to:
x = x + x--;

Which is equivalent to:

int a1 = x; // a1 = 10, x = 10
int a2 = x--; // a2 = 10, x = 9
x = a1 + a2; // x = 20

So x is 20 afterwards - and that's guaranteed by the spec.



  • 1) subexpressions are always evaluated left to right. Period. Evaluation of a subexpression may induce a side effect.


2) execution of operators is always done in the order indicated by parentheses, precedence and associativity. Execution of operators may induce a side effect.

The "x" to the left of the += is the leftmost subexpression, and therefore rule (1) applies. Its value is computed first -- 10.

The x-- to the right of the += is the next one in left-to-right order, so it is evaluated next. The value of x-- is 10, and the side effect is that x becomes 9. This is as it should be, because -- is of higher precedence than +=, so its side effect runs first.

Finally, the side effect of += runs last. The two operands were 10 and 10, so the result is to assign 20 to x.

I get questions about this all the time. Remember, the rules are very straightforward: subexpressions left-to-right, operators in precedence order, period.



  • a difference between --x and x-- here. 

If you had written x += --x;
this would be equivalent to x = x + --x;
then you would get 19.
This is because the value of x is decremented and the resulting value is used in the expression
(unlike x-- where the original value of x is used in the expression).

This expression x = x + --x + x will give 28 because the third timefourth time (see comments) x is evaluated it is 9.



http://stackoverflow.com/questions/2299437/int-x-10-x-x-in-net-why

Two-dimensional array



int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);

http://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx

Static Classes


A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.80%29.aspx

sealed class


A sealed class cannot be inherited. It is an error to use a sealed class as a base class. Use the sealed modifier in a class declaration to prevent inheritance of the class.

Abstract Class in C#

An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.
http://msdn.microsoft.com/en-us/library/ms173150%28v=vs.80%29.aspx

Friday, January 25, 2013

Harvard architecture


Harvard architecture
The Harvard architecture is a computer architecture with physically separate storage and signal pathways for instructions and data.
The term originated from the Harvard Mark I relay-based computer, which stored instructions on punched tape (24 bits wide) and data in electro-mechanical counters. These early machines had data storage entirely contained within the central processing unit, and provided no access to the instruction storage as data.
Programs needed to be loaded by an operator; the processor could not boot itself.
Today, most processors implement such separate signal pathways for performance reasons but actually implement a modified Harvard architecture, so they can support tasks such as loading a program from disk storage as data and then executing it.
http://en.wikipedia.org/wiki/Harvard_architecture

CISC


CISC
A complex instruction set computer CISC
A complex instruction set computer (CISC) is a computer where single instructions can execute several low-level operations (such as a load from memory, an arithmetic operation, and a memory store) and/or are capable of multi-step operations or addressing modes within single instructions.
The term was retroactively coined in contrast to reduced instruction set computer (RISC)

Examples of CISC instruction set architectures are System/360 through z/Architecture, PDP-11, VAX, Motorola 68k, and x86.
http://en.wikipedia.org/wiki/Complex_instruction_set_computing

RISC


RISC
Reduced instruction set computing, or RISC  is a CPU design strategy based on the insight that simplified (as opposed to complex) instructions can provide higher performance if this simplicity enables much faster execution of each instruction.
A computer based on this strategy is a reduced instruction set computer, also called RISC.
The opposing architecture is known as complex instruction set computing, i.e. CISC.

Well known RISC families include DEC Alpha, AMD 29k, ARC, ARM, Atmel AVR, Blackfin, Intel i860 and i960, MIPS, Motorola 88000, PA-RISC, Power (including PowerPC), SuperH, and SPARC
http://en.wikipedia.org/wiki/Reduced_instruction_set_computing

Fuzzy logic


Fuzzy logic
Fuzzy logic iss a form of many-valued logic or probabilistic logic; it deals with reasoning that is approximate rather than fixed and exact.
Compared to traditional binary sets (where variables may take on true or false values) fuzzy logic variables may have a truth value that ranges in degree between 0 and 1.
Fuzzy logic has been extended to handle the concept of partial truth, where the truth value may range between completely true and completely false
http://en.wikipedia.org/wiki/Fuzzy_logic

  • Fuzzy Logic (FL) is a method of reasoning that resembles human reasoning. The approach of FL imitates the way of decision making in humans that involves all intermediate possibilities between digital values YES and NO.
The conventional logic block that a computer can understand takes precise input and produces a definite output as TRUE or FALSE, which is equivalent to human’s YES or NO.
http://www.tutorialspoint.com/artificial_intelligence/artificial_intelligence_fuzzy_logic_systems.htm

  • In this work, we focus   the   detection   and   prediction   mechanism   against DDoS  attacks  in  IEEE  802.15.4  using  Fuzzy  logic  system. The   main   contribution   of   Fuzzy   based   detection   and prediction system (FBDPS) is to detect the DDoS attackers
by comparing the energy consumption of sensor nodes.
http://ijcsi.org/papers/IJCSI-10-6-1-293-301.pdf

Thursday, January 17, 2013

infix prefix postfix notations


Infix notation

Infix notation is the common arithmetic and logical formula notation, in which operators are written infix-style between the operands they act on (e.g. 2 + 2)
It is not as simple to parse by computers as prefix notation ( e.g. + 2 2 ) or postfix notation ( e.g. 2 2 + ), but many programming languages use it due to its familiarity

In infix notation, unlike in prefix or postfix notations, parentheses surrounding groups of operands and operators are necessary to indicate the intended order in which operations are to be performed. In the absence of parentheses, certain precedence rules determine the order of operations.

http://en.wikipedia.org/wiki/Infix_notation


Prefix notation
Polish notation, also known as Polish prefix notation or simply prefix notation, is a form of notation for logic, arithmetic, and algebra. Its distinguishing feature is that it places operators to the left of their operands.

http://en.wikipedia.org/wiki/Polish_notation


Postfix notation
Reverse Polish notation (RPN) is a mathematical notation in which every operator follows all of its operands, in contrast to Polish notation, which puts the operator in the prefix position.

http://en.wikipedia.org/wiki/Reverse_Polish_notation



Monday, January 14, 2013

What's the difference between throw, throwable & throws?



throw and throws are java keywords and Throwable is a super class for errors and exceptions.
Only the objects of the Throwable can be thrown by the “throws” or “throw” statement.

throws :
used on the method to specify than an exception(s) can be thrown. The throws clause tells the complier that this particular exception would be handled by the calling method.

throw :
it is a statement to throw the exception when certain condition is failed or other logic had returned exception. This can be used in any part of code where you feel a specific exception needs to be thrown to the calling method

http://www.linkedin.com/groups/Whats-difference-between-throw-throwable-70526.S.200485518?view=&srchtype=discussedNews&gid=70526&item=200485518&type=member&trk=eml-anet_dig-b_pd-ttl-cn&ut=17ZTwoVDpUpBA1

Wednesday, December 19, 2012

what is middleware?


middleware is computer software that provides services to software applications beyond those available from the operating system.
The term is most commonly used for software that enables communication and management of data in distributed applications.
Services that can be regarded as middleware include enterprise application integration, data integration, message oriented middleware (MOM), object request brokers (ORBs), and the enterprise service bus (ESB).
http://en.wikipedia.org/wiki/Middleware

Wednesday, December 5, 2012

mysql installation


MySQL community server database,  mysql connector, mysql workbench download

MySQL Community Server: http://dev.mysql.com/downloads/mysql/


MySQL Connector/J : http://dev.mysql.com/downloads/connector/j/


MySQL Workbench : http://dev.mysql.com/downloads/workbench/


mysql connection glass fish server config

Copy the MySQL Connector/j jar file into your glassfish lib folder.
On windows, this folder is located at ‘glassfish installation location’\glassfish\modules.

http://www.greenkode.com/2011/08/install-and-configure-mysql-for-eclipse-and-oracle-glassfish-3-1/



mysql connection pool-glassfish-eclipse config

https://blogs.oracle.com/davisn/entry/create_mysql_jdbc_connection_pool





  • Download and Install MySQL




For Windows

    Download MySQL from www.mysql.com ? Select top-level tab "Downloads (GA)" ? MySQL Community Edition (GPL):
        Under "MySQL Community Server (GPL)" ? Select DOWNLOAD.
        Under "General Available (GA) Release", "MySQL Community Server 5.6.{xx}" (where {xx} is the latest upgrade number) ? In "Select Platform", Select "Microsoft Windows".
        Download the 32-bit or 64-bit ZIP Archive (mysql-5.6.{xx}-win32.zip or mysql-5.6.{xx}-winx64.zip, about 210 MB).
        You can check whether your Windows is 32-bit or 64-bit from "Control Panel" ? System ? System Type.
        There is NO need to "Sign-up" - Just click "No thanks, just start my downloads!".
    UNZIP into a directory of your choice. DO NOT unzip into your desktop (because it is hard to locate the path). I suggest that you unzip into "d:\myProject" (or "c:\myproject" if you do not have a D drive). MySQL will be unzipped as "d:\myProject\mysql-5.5.{xx}-win32". For ease of use, we shall shorten and rename the directory to "d:\myProject\mysql".


I recommend using the "ZIP" version, instead of the "Windows Installer" version for academic learning. You can simply delete the entire MySQL directory when it is no longer needed (without running the un-installer). You are free to move or rename the directory. You can also install (unzip) multiple copies of MySQL in the same machine on different directories.

(For Advanced Users Only) A better approach is to keep the original folder name, such as mysql-5.6.{xx}-win32, but create a symlink called mysql via command "mklink /D mysql mysql-5.6.{xx}-win32". Symlink is available in Windows Vista/7/8.


MySQL Distribution

The MySQL distribution includes:

    A SQL server (mysqld);
    A command-line client (mysql);
    Utilities: Database administration (mysqladmin), backup/restore (mysqldump), and others;
    Client libraries for you to write your own client.


Explanation

    [mysqld]
    [client]
    The MySQL operates as a client-server system, and consists of a server program and a client program. There are two sections in the configuration: [mysqld] for the server program, and [client] for the client program.
    basedir=<MYSQL_HOME>
    datadir=<MYSQL_HOME>/data
    "basedir" and "datadir" specify the MySQL installed directory and data directory for storing the databases, respectively. Make sure that you set their values according to your own installation. You need to use Unix-style forward-slash (/) as the directory separator, instead of Windows-style backward-slash (\).
    port=8888
    MySQL is a TCP/IP application. The default TCP port number for MySQL is 3306. However, it may crash with a MySQL server already running in some lab machines. You may choose any port number between 1024 to 65535, which is not used by an existing application. I choose 8888 for our server.
    This configuration file specifies the bare minimum. There are many more configuration options. Sample configuration files (*.ini, *.cnf) are provided under <MYSQL_HOME>.

The server program is called "mysqld" (with a suffix 'd', which stands for daemon - a daemon is a non-interactive process running in the background).
The client program is called "mysql" (without the 'd')


http://www.ntu.edu.sg/home/ehchua/programming/sql/MySQL_HowTo.html

Wednesday, November 28, 2012

Refactoring › Composing Methods -Extract Method

  • You have a code fragment that can be grouped together.

Turn the fragment into a method whose name explains the purpose of the method.

Example: No Local Variables

before
 // print banner
    System.out.println ("**************************");
    System.out.println ("***** Customer Owes ******");
    System.out.println ("**************************");


after

printBanner();

void printBanner() {
    // print banner
    System.out.println ("**************************");
    System.out.println ("***** Customer Owes ******");
    System.out.println ("**************************");
}

http://sourcemaking.com/refactoring/extract-method



  • The Extract Method refactoring has the following limitations:


    Refactoring does not work with multiple output values in automatic mode. You have to change your code before applying the refactoring.
    Refactoring does not work for a code fragment which conditionally returns from the containing method and is not placed at the end of it.

before (eclipse)

  public class ExtractMethod1 {

public static void main(String[] args) {
method1();
}



 static void method1() {
   int a=1;
   int b=2;
   int c=a+b;
   int d=a+c;
}
}




after (eclipse)

public class ExtractMethod1 {

public static void main(String[] args) {

method1();
}



 static void method1() {
   getSum();
}



private static void getSum() {
int a=1;
int b=2;
int c=a+b;
int d=a+c;
}
}


In Eclipse you select the code fragment you want to refactor,right click,refactor and extract method


before (IntelliJ IDEA 11.1)

  public class ExtractMethod1 {

public static void main(String[] args) {
method1();
}



 static void method1() {
   int a=1;
   int b=2;
   int c=a+b;
   int d=a+c;
}
}


after (IntelliJ IDEA 11.1)

public class ExtractMethod1 {


public static void main(String[] args) {

method1();
}



 static void method1() {
   int a=1;
int b=2;
int c=add(a,b);
int d=add(a,c);
}


private static int add(int a,int b) {
return a+b;
}
}



before (IntelliJ IDEA 11.1)

ArrayList method2()
{
String[] strings={"a","b","c","d"};
ArrayList list=new ArrayList();

for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
return list;
}

}


after (IntelliJ IDEA 11.1)

private ArrayList add(String[] strings)
{
ArrayList list=new ArrayList();

for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
return list;
}


http://www.jetbrains.com/idea/webhelp/extract-method.html#h2example



  • Extract Method


The Extract Method refactoring allows you to select a block of code and convert it to a method. Eclipse automatically infers the method arguments and return types.
This is useful when a method is too big and you want to subdivide blocks of it into different methods. It is also useful if you have a piece of code that is reused across many methods. When you select one of those blocks of code and do a refactoring, Eclipse finds other occurrences of that block of code and replaces it with a call to the new method.

Listing 3. Before Extract Method refactoring

@Override
public Object get(Object key)
{
TimedKey timedKey = new TimedKey(System.currentTimeMillis(), key);
Object object = map.get(timedKey);

if (object != null)
{
/**
* if this was removed after the 'get' call by the worker thread
* put it back in
*/
map.put(timedKey, object);
return object;
}

return null;
}



Listing 4. After Before Extract Method refactoring

@Override
public Object get(Object key)
{
TimedKey timedKey = new TimedKey(System.currentTimeMillis(), key);
Object object = map.get(timedKey);

return putIfNotNull(timedKey, object);
}

private Object putIfNotNull(TimedKey timedKey, Object object)
{
if (object != null)
{
/**
* if this was removed after the 'get' call by the worker thread
* put it back in
*/
map.put(timedKey, object);
return object;
}

return null;
}
http://www.ibm.com/developerworks/opensource/library/os-eclipse-refactoring/index.html

Refactoring


Defining Refactoring
 
 
    Refactoring (noun): a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.

The other usage of refactoring is the verb form
    Refactor (verb): to restructure software by applying a series of refactorings without changing its observable behavior.

“Is refactoring just cleaning up code?” In a way the answer is yes, but I think refactoring goes further because it provides a technique for cleaning up code in a more efficient and controlled manner

 the purpose of refactoring is to make the software easier to understand and modify.
 Only changes made to make the software easier to understand are refactorings
 Like refactoring, performance optimization does not usually change the behavior of a component (other than its speed); it only alters the internal structure
 the purpose is different. Performance optimization often makes code harder to understand, but you need to do it to get the performance you need.
 The software still carries out the same function that it did before

 When you use refactoring to develop software, you divide your time between two distinct activities: adding function and refactoring

 When you add function, you shouldn’t be changing existing code; you are just adding new capabilities. You can measure your progress by adding tests and getting the tests to work
 When you refactor, you make a point of not adding function; you only restructure the code. You don’t add any tests (unless you find a case you missed earlier)

 http://sourcemaking.com/refactoring/defining-refactoring




Why Should You Refactor?
The harder it is to see the design in the code, the harder it is to preserve it, and the more rapidly it decays. Regular refactoring helps code retain its shape.
By eliminating the duplicates, you ensure that the code says everything once and only once, which is the essence of good design.

Refactoring Makes Software Easier to Understand
Refactoring helps you to make your code more readable.
Ralph Johnson describes these early refactorings as wiping the dirt off a window so you can see beyond.
http://sourcemaking.com/refactoring/why-should-you-refactor


Refactoring Helps You Program Faster
When I talk about refactoring, people can easily see that it improves quality. Improving design, improving readability, reducing bugs, all these improve quality. But doesn’t all this reduce the speed of development?
the whole point of having a good design is to allow rapid development. Without a good design, you can progress quickly for a while, but soon the poor design starts to slow you down.
http://sourcemaking.com/refactoring/refactoring-helps-you-find-bugs


When Should You Refactor?
In my view refactoring is not an activity you set aside time to do. Refactoring is something you do all the time in little bursts

The Rule of Three
he first time you do something, you just do it.
The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway.
The third time you do something similar, you refactor.

Refactor When You Add Function
The most common time to refactor is when I want to add a new feature to some software
This code may have been written by someone else, or I may have written it
 Whenever I have to think to understand what the code is doing, I ask myself if I can refactor the code to make that understanding more immediately apparent

 I look at the design and say to myself, “If only I’d designed the code this way, adding this feature would be easy.” In this case I don’t fret over my past misdeeds—I fix them by refactoring

 Refactor When You Need to Fix a Bug
 As I look at the code trying to understand it, I refactor to help improve my understanding.
 if you do get a bug report, it’s a sign you need refactoring, because the code was not clear enough for you to see there was a bug


Refactor As You Do a Code Review
Reviews help more experienced developers pass knowledge to less experienced people
My code may look clear to me but not to my team.
This idea of active code review is taken to its limit with the Extreme Programming [Beck, XP] practice of Pair Programming

Why Refactoring Works
Kent Beck

Programs have two kinds of value: what they can do for you today and what they can do for you tomorrow. Most times when we are programming, we are focused on what we want the program to do today. Whether we are fixing a bug or adding a feature, we are making today’s program more valuable by making it more capable

If you can get today’s work done today, but you do it in such a way that you can’t possibly get tomorrow’s work done tomorrow, then you lose.

http://sourcemaking.com/refactoring/when-should-you-refactor


Changing Interfaces
Something that is disturbing about refactoring is that many of the refactorings do change an interface. Something as simple as Rename Method is all about changing an interface. So what does this do to the treasured notion of encapsulation?



You should also use the deprecation facility in Java to mark the code as deprecated. That way your callers will know that something is up.
A good example of this process is the Java collection classes. The new ones present in Java 2 supersede the ones that were originally provided

When Shouldn’t You Refactor?
There are times when you should not refactor at all. The principle example is when you should rewrite from scratch instead. There are times when the existing code is such a mess that although you could refactor it, it would be easier to start from the beginning.

The other time you should avoid refactoring is when you are close to a deadline. At that point the productivity gain from refactoring would appear after the deadline and thus be too late

http://sourcemaking.com/refactoring/problems-with-refactoring

Friday, November 23, 2012

10 Object Oriented Design principles Java programmer should know


10 Object Oriented Design principles Java programmer should know

Object oriented design principle 1 -  DRY (Don't repeat yourself)
Object oriented design principle 2 - Encapsulate what varies
Object oriented design principle 3 - Open Closed principle
Object oriented design principle 4 - Single Responsibility Principle (SRP)
Object oriented design principle 5 - Dependency Injection or Inversion principle
Object oriented design principle 6 - Favour Composition over Inheritance
Object oriented design principle 7 - Liskov Substitution Principle (LSP)
Object oriented design principle 8 - Interface Segregation principle (ISP)
Object oriented design principle 9 - Programming for Interface not implementation
Object oriented design principle 10 - Delegation principle

http://javarevisited.blogspot.com/2012/03/10-object-oriented-design-principles.html#ixzz2D4RM6ys7


  • In software engineering, don't repeat yourself (DRY) is a principle of software development aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures. The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

http://en.wikipedia.org/wiki/DRY_code

The ? : operator in Java


if (a > b) {
  max = a;
}
else {
  max = b;
}

or shortly

max = (a > b) ? a : b;

http://www.cafeaulait.org/course/week2/43.html

Wednesday, November 21, 2012

web service interview questions

1) Define Web Service?
A web service is a kind of software that is accessible on the Internet. It makes use of the XML messaging system and offers an easy to understand, interface for the end users.

3) Give me an example of real web service?
Basically web services can be used with the help of SOAP, WSDL, and UDDI . All these, provide a plug-and-play interface for using web services such as stock-quote service, a traffic-report service,  weather service etc.

7) Define SOAP?

SOAP is an XML based protocol to transfer between computers.


8) Define WSDL?

It means Web Services Description Language. It is basically the service description layer in the web service protocol stock. The Service Description layer describes the user interface to a web service.

17) Differentiate between a SOA and a Web service?

SOA is a design and architecture to implement other services. SOA can be easily implemented using various protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP, RPC etc. While Web service, itself is an implemented technology. In fact one can implement SOA using the web service.

23) What is REST?

REST stands for Representational State Transfer. REST itself is not a standard, while it uses various standards such as HTTP, URL, XML/HTML/GIF/JPEG (Resource Representations) and text/xml, text/html, image/gif, image/jpeg, etc (MIME Types).


25) Name the various communication channels in web service?

Web service is integrated with three protocols such as HTTP/POST, HTTP/GET, and SOAP. It provides three different communication channels to clients. Client can choose any communication method as per requirements.



29) Differentiate between web services, CORBA and DCOM?

Web services transfer/receive messages to/from application respectively, via HTTP protocol. It uses XML to encode data.

CORBA and DCOM transfer/receive messages to/from application respectively, via non-standard protocols such as IIOP and RPC.



31) Can you name some standards used in web services?

The standards used in web services are WSDL (used to create interface definition), SOAP (used to structure data), HTTP (communication channels), DISCO (used to create discovery documents) and UDDI (used to create business registries).


33) Explain in brief, what UDDI is?

UDDI (Universal Description, Discovery, and Integration) provides consolidated directory for web services on the internet. Clients use UDDI to find web services as per their business needs. It basically hosts the web services from various companies. In order to share web services, you need to publish it in UDDI.

40) What are the steps performed by the client to access a web service?

First of all a web reference to the web service is created by the client in his application. Then a proxy class is generated. After that an object of the proxy class is created and at last, the web service is accessed via that proxy object.


44) Brief few drawbacks of using GET and POST methods to communicate with the web service?

These methods are less secure and inhibit users to pass structures and objects as arguments. Also, it doesn’t allow users to pass ByRef arguments.


48) Can you name different kinds of web services?

There are two types of web services in total i.e. SOAP based web service and RESTful web service.


49) What’s different in RESTful web services?

The RESTful web services contains no contract or WSDL file.


50) Give me few reasons to use RESTful web service?

The RESTFul web services are simple to implement and test. It supports various data formats such as XML, JSON etc.


http://www.gointerviews.com/top-50-web-services-interview-questions/


What is WSDL?


WSDL is an XML-based language for describing Web services and how to access them.

WSDL Describes Web Services

WSDL stands for Web Services Description Language.

WSDL is a document written in XML. The document describes a Web service. It specifies the location of the service and the operations (or methods) the service exposes.

http://www.w3schools.com/wsdl/wsdl_intro.asp


Does Web Service call is synchronous or asynchronous ?

An asynchronous web service allows a client to submit a request, process the request and respond to the client after a given time -- the client would not block all activity on receiving a response.

Comparatively, a web service that is synchronous would provide a client directly with a response, expecting the client to block all activity until a response is returned. In this case the web service would limit the client to process requests one at a time.


What is the difference between Java RMI and JMS?

RMI is a form of Remote Procedure Call (RPC). It is a lightweight, Java specific API that expects the caller and receiver to be available at the time of communication.

JMS is a reliable messaging subsystem. Messages can be passed even if one of the parties is not available. It is an alternative to things like MQSeries.

RMI doesn't deal with guaranteed delivery or asynchronous responses, JMS does.




difference between RMI, WebService, CORBA

RMI is Java's native method of invoking methods on objects that are located in a different JVM - Remote Method Invocation. It passes objects over the wire in binary, and can run either over the JRMP (Java Remote Method Protocol) or via IIOP (CORBA's Internet Inter-ORB Protocol)

CORBA is a language neutral remote method invocation protocol specified by the OMG standards group, and works with C/C++, Smalltalk, etc as well as with Java. CORBA laos sends data across the wire in binary format, and specifies interfaces in a scheme known as IDL (Interface Definition Language)

Web Services are remote invocations that are sent across the wire usually via SOAP (a flavour of XML data) over HTTP, but they can also go as SOAP/JMS, or other bindings - SMTP, etc

inheritance vs composition

About inheritance
In this article, I'll be talking about single inheritance through class extension, as in:

class Fruit {

    //...
}

class Apple extends Fruit {

    //...
}

In this simple example, class Apple is related to class Fruit by inheritance, because Apple extends Fruit. In this example, Fruit is the superclass and Apple is the subclass.



bout composition
By composition, I simply mean using instance variables that are references to other objects. For example:

class Fruit {

    //...
}

class Apple {

    private Fruit fruit = new Fruit();
    //...
}

In the example above, class Apple is related to class Fruit by composition, because Apple has an instance variable that holds a reference to a Fruit object. In this example, Apple is what I will call the front-end class and Fruit is what I will call the back-end class. In a composition relationship, the front-end class holds a reference in one of its instance variables to a back-end class.

The composition alternative
Given that the inheritance relationship makes it hard to change the interface of a superclass, it is worth looking at an alternative approach provided by composition. It turns out that when your goal is code reuse, composition provides an approach that yields easier-to-change cod


http://www.artima.com/designtechniques/compoinh.html

inheritance vs delegation java

  • inheritance vs  delegation java


Inheritance is used to create a hierarchical-type code structure that tries to keep as much “common” code near the top of the hierarchy.
In small, static systems, inheritance can be ok.
But large inheritance chains can also lead to hard-to-maintain code
design patterns that favor composition over inheritance for more info when to use inheritance and when not to.

Delegation is simply passing a duty off to someone/something else.
Delegation is alternative to inheritance.
Delegation means that you use an object of another class as an instance variable, and forward messages to the instance.


It is better than inheritance because it makes you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class
you can provide only the methods that really make sense.
Delegation can also a powerful design/reuse technique.
The primary advantage of delegation is run-time flexibility
the delegate can easily be changed at run-time.


the choice between delegation and inheritance is driven by external factors such as programming language support for multiple inheritance or design constraints requiring polymorphism.

Consider threads in Java. You can associate a class with a thread in one of two ways: either by extending (inheriting) directly from class Thread, or by implementing the Runnable interface and then delegating to a Thread object

Often the approach taken is based on the restriction in Java that a class can only extend one class (i.e., Java does not support multiple inheritance). If the class you want to associate with a thread already extends some other class in the design, then you would have to use delegation; otherwise, extending class Thread would usually be the simpler approach

http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html#ixzz2CqNmtYMM

Lazy initialization

  • Lazy initialization
In computer programming, 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.

In a software design pattern view, lazy initialization is often used together with a factory method pattern. This combines three ideas:

    using a factory method to get instances of a class (factory method pattern)
    storing the instances in a map, so you get the same instance the next time you ask for an instance with same parameter (Multiton pattern, similar to the singleton pattern)
    using lazy initialization to instantiate the object the first time it is requested (lazy initialization pattern).

http://en.wikipedia.org/wiki/Lazy_initialization#Java





  • Lazy initialization is a performance optimization.

if the hashCode value for an object might not actually be needed by its caller, always calculating the hashCode for all instances of the object may be felt to be unnecessary.
since accessing a file system or network is relatively slow, such operations should be put off until they are absolutely required.

Lazy initialization has two objectives :

    delay an expensive operation until it's absolutely necessary
    store the result of that expensive operation, such that you won't need to repeat it again

http://www.javapractices.com/topic/TopicAction.do?Id=34

Tuesday, November 20, 2012

Memento pattern




  • Memento Design Pattern


Intent

    Without violating encapsulation, capture and externalize an object’s internal state so that the object can be returned to this state later.
    A magic cookie that encapsulates a “check point” capability.
    Promote undo or rollback to full object status.


Rules of thumb


    Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
    Command can use Memento to maintain the state required for an undo operation.
    Memento is often used in conjunction with Iterator. An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally.
http://sourcemaking.com/design_patterns/memento




  • Memento pattern


The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).

The memento pattern is implemented with two objects: the originator and a caretaker. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources - the memento pattern operates on a single object.

Classic examples of the memento pattern include the seed of a pseudorandom number generator (it will always produce the same sequence thereafter when initialized with the seed state) and the state in a finite state machine.

http://en.wikipedia.org/wiki/Memento_pattern

Template Method Pattern



  • Template Method Design Pattern

Intent

    Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Rules of thumb

    Strategy is like Template Method except in its granularity.
    Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
    Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.
    Factory Method is a specialization of Template Method.
http://sourcemaking.com/design_patterns/template_method



  • Template method pattern

 the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure
 http://en.wikipedia.org/wiki/Template_method_pattern

State pattern



  • State Design Pattern


Intent

    Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
    An object-oriented state machine
    wrapper + polymorphic wrappee + collaboration


Example


The State pattern allows an object to change its behavior when its internal state changes. This pattern can be observed in a vending machine. Vending machines have states based on the inventory, amount of currency deposited, the ability to make change, the item selected, etc. When currency is deposited and a selection is made, a vending machine will either deliver a product and no change, deliver a product and change, deliver no product due to insufficient currency on deposit, or deliver no product due to inventory depletion.


Rules of thumb

    State objects are often Singletons.
    Flyweight explains when and how State objects can be shared.
    Interpreter can use State to define parsing contexts.
    Strategy has 2 different implementations, the first is similar to State. The difference is in binding times (Strategy is a bind-once pattern, whereas State is more dynamic).
    The structure of State and Bridge are identical (except that Bridge admits hierarchies of envelope classes, whereas State allows only one). The two patterns use the same structure to solve different problems: State allows an object’s behavior to change along with its state, while Bridge’s intent is to decouple an abstraction from its implementation so that the two can vary independently.
    The implementation of the State pattern builds on the Strategy pattern. The difference between State and Strategy is in the intent. With Strategy, the choice of algorithm is fairly stable. With State, a change in the state of the “context” object causes it to select from its “palette” of Strategy objects.

http://sourcemaking.com/design_patterns/state




  • State pattern

The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to represent the state of an object. This is a clean way for an object to partially change its type at runtime
http://en.wikipedia.org/wiki/State_pattern

Null Object pattern



  • Null Object pattern

a Null Object is an object with defined neutral ("null") behavior.
The Null Object design pattern describes the uses of such objects and their behavior (or lack thereof).

Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects: it does nothing.

For example, a function may retrieve a list of files in a directory and perform some action on each. In the case of an empty directory, one response may be to throw an exception or return a null reference rather than a list. Thus, the code which expects a list must verify that it in fact has one before continuing, which can complicate the design.

By returning a null object (i.e. an empty list) instead, there is no need to verify that the return value is in fact a list. The calling function may simply iterate the list as normal, effectively doing nothing. It is, however, still possible to check whether the return value is a null object (e.g. an empty list) and react differently if desired.

The null object pattern can also be used to act as a stub for testing if a certain feature, such as a database, is not available for testing.

http://en.wikipedia.org/wiki/Null_Object_pattern



  • Rules of thumb


    The Null Object class is often implemented as a Singleton. Since a null object usually does not have any state, its state can’t change, so multiple instances are identical. Rather than use multiple identical instances, the system can just use a single instance repeatedly.
    If some clients expect the null object to do nothing one way and some another, multiple NullObject classes will be required. If the do nothing behavior must be customized at run time, the NullObject class will require pluggable variables so that the client can specify how the null object should do nothing (see the discussion of pluggable adaptors in the Adapter pattern). This may generally be a symptom of the AbstractObject not having a well defined (semantic) interface.
    A Null Object does not transform to become a Real Object. If the object may decide to stop providing do nothing behavior and start providing real behavior, it is not a null object. It may be a real object with a do nothing mode, such as a controller which can switch in and out of read-only mode. If it is a single object which must mutate from a do nothing object to a real one, it should be implemented with the State pattern or perhaps the Proxy pattern. In this case a Null State may be used or the proxy may hold a Null Object.
    The use of a null object can be similar to that of a Proxy, but the two patterns have different purposes. A proxy provides a level of indirection when accessing a real subject, thus controlling access to the subject. A null collaborator does not hide a real object and control access to it, it replaces the real object. A proxy may eventually mutate to start acting like a real subject. A null object will not mutate to start providing real behavior, it will always provide do nothing behavior.
    A Null Object can be a special case of the Strategy pattern. Strategy specifies several ConcreteStrategy classes as different approaches for accomplishing a task. If one of those approaches is to consistently do nothing, that ConcreteStrategy is a NullObject. For example, a Controller is a View’s Strategy for handling input, and NoController is the Strategy that ignores all input.
    A Null Object can be a special case of the State pattern. Normally, each ConcreteState has some do nothing methods because they’re not appropriate for that state. In fact, a given method is often implemented to do something useful in most states but to do nothing in at least one state. If a particular ConcreteState implements most of its methods to do nothing or at least give null results, it becomes a do nothing state and as such is a null state.
    A Null Object can be used to allow a Visitor to safely visit a hierarchy and handle the null situation.
    Null Object is a concrete collaborator class that acts as the collaborator for a client which needs one. The null behavior is not designed to be mixed into an object that needs some do nothing behavior. It is designed for a class which delegates to a collaborator all of the behavior that may or may not be do nothing behavior
   
    http://sourcemaking.com/design_patterns/null_object

Mediator pattern



  • Mediator Design Pattern

Intent

    Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
    Design an intermediary to decouple many peers.
    Promote the many-to-many relationships between interacting peers to “full object status”.
   
Example

The Mediator defines an object that controls how a set of objects interact. Loose coupling between colleague objects is achieved by having colleagues communicate with the Mediator, rather than with each other. The control tower at a controlled airport demonstrates this pattern very well. The pilots of the planes approaching or departing the terminal area communicate with the tower rather than explicitly communicating with one another. The constraints on who can take off or land are enforced by the tower. It is important to note that the tower does not control the whole flight. It exists only to enforce constraints in the terminal area.

Rules of thumb

    Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers. Command normally specifies a sender-receiver connection with a subclass. Mediator has senders and receivers reference each other indirectly. Observer defines a very decoupled interface that allows for multiple receivers to be configured at run-time.
    Mediator and Observer are competing patterns. The difference between them is that Observer distributes communication by introducing “observer” and “subject” objects, whereas a Mediator object encapsulates the communication between other objects. We’ve found it easier to make reusable Observers and Subjects than to make reusable Mediators.
    On the other hand, Mediator can leverage Observer for dynamically registering colleagues and communicating with them.
    Mediator is similar to Facade in that it abstracts functionality of existing classes. Mediator abstracts/centralizes arbitrary communication between colleague objects, it routinely “adds value”, and it is known/referenced by the colleague objects (i.e. it defines a multidirectional protocol). In contrast, Facade defines a simpler interface to a subsystem, it doesn’t add new functionality, and it is not known by the subsystem classes (i.e. it defines a unidirectional protocol where it makes requests of the subsystem classes but not vice versa).
http://sourcemaking.com/design_patterns/mediator



  • Mediator pattern

The mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.
http://en.wikipedia.org/wiki/Mediator_pattern

Interpreter Pattern


Interpreter Design Pattern

Intent

    Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
    Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design.

Rules of thumb
    Considered in its most general form (i.e. an operation distributed over a class hierarchy based on the Composite pattern), nearly every use of the Composite pattern will also contain the Interpreter pattern. But the Interpreter pattern should be reserved for those cases in which you want to think of this class hierarchy as defining a language.
    Interpreter can use State to define parsing contexts.
    The abstract syntax tree of Interpreter is a Composite (therefore Iterator and Visitor are also applicable).
    Terminal symbols within Interpreter’s abstract syntax tree can be shared with Flyweight.
    The pattern doesn’t address parsing. When the grammar is very complex, other techniques (such as a parser) are more appropriate.


http://sourcemaking.com/design_patterns/interpreter


Interpreter pattern
the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence
http://en.wikipedia.org/wiki/Interpreter_pattern

Chain of Responsibility Pattern



  • Rules of thumb


    Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers.
    Chain of Responsibility can use Command to represent requests as objects.
    Chain of Responsibility is often applied in conjunction with Composite. There, a component’s parent can act as its successor
http://sourcemaking.com/design_patterns/chain_of_responsibility



  • Chain-of-responsibility pattern

the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern

Monday, November 19, 2012

Command pattern



  • Command pattern

command pattern is a behavioural design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

Three terms always associated with the command pattern are client, invoker and receiver. The client instantiates the command object and provides the information required to call the method at a later time. The invoker decides when the method should be called. The receiver is an instance of the class that contains the method's code.

http://en.wikipedia.org/wiki/Command_pattern




  • Rules of thumb



    Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Command normally specifies a sender-receiver connection with a subclass.
    Chain of Responsibility can use Command to represent requests as objects.
    Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
    Command can use Memento to maintain the state required for an undo operation.
    MacroCommands can be implemented with Composite.
    A Command that must be copied before being placed on a history list acts as a Prototype.
    Two important aspects of the Command pattern: interface separation (the invoker is isolated from the receiver), time separation (stores a ready-to-go processing request that’s to be stated later)
http://sourcemaking.com/design_patterns/command

Prototype Pattern



  • Prototype Pattern


Intent

    Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
    The new operator considered harmful.

Rules of thumb


    Sometimes creational patterns are competitors: there are cases when either Prototype or Abstract Factory could be used properly. At other times they are complementory: Abstract Factory might store a set of Prototypes from which to clone and return product objects. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
    Abstract Factory classes are often implemented with Factory Methods, but they can be implemented using Prototype.
    Factory Method: creation through inheritance. Protoype: creation through delegation.
    Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Protoype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
    Prototype doesn’t require subclassing, but it does require an “initialize” operation. Factory Method requires subclassing, but doesn’t require Initialize.
    Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well.
    Prototype co-opts one instance of a class for use as a breeder of all future instances.
    Prototypes are useful when object initialization is expensive, and you anticipate few variations on the initialization parameters. In this context, Prototype can avoid expensive “creation from scratch”, and support cheap cloning of a pre-initialized prototype.
    Prototype is unique among the other creational patterns in that it doesn’t require a class – only an object. Object-oriented languages like Self and Omega that do away with classes completely rely on prototypes for creating new objects

http://sourcemaking.com/design_patterns/prototype



  • Prototype pattern


The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:

    avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
    avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.

http://en.wikipedia.org/wiki/Prototype_pattern

Object Pool Pattern



  • Object Pool Design Pattern


Intent

Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.

Problem

Object pools (otherwise known as resource pools) are used to manage the object caching. A client with access to a Object pool can avoid creating a new Objects by simply asking the pool for one that has already been instantiated instead. Generally the pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty, or we can have a pool, which restricts the number of objects created.


Example

Do you like bowling? If you do, you probably know that you should change your shoes when you getting the bowling club. Shoe shelf is wonderful example of Object Pool. Once you want to play, you’ll get your pair (aquireReusable) from it. After the game, you’ll return shoes back to the shelf (releaseReusable).

Rules of thumb

    The Factory Method pattern can be used to encapsulate the creation logic for objects. However, it does not manage them after their creation, the object pool pattern keeps track of the objects it creates.
    Object Pools are usually implemented as Singletons.

http://sourcemaking.com/design_patterns/object_pool



  • Object pool pattern


The object pool pattern is a software creational design pattern that uses a set of initialised objects kept ready to use, rather than allocating and destroying them on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished, it returns the object, which is a specific type of factory object, to the pool rather than destroying it

http://en.wikipedia.org/wiki/Object_pool_pattern



  • Object Pool Pattern

The Object Pool lets others "check out" objects from its pool, when those objects are no longer needed by their processes, they are returned to the pool in order to be reused.
http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/objectpool.html