CSS

CSS

Cascading Style Sheets (CSS) is a style sheet language used to describe the presentation semantics (that is, the look and formatting) of a document written in a markup language. The most common application is to style web pages written in HTML and XHTML, but the language can also be applied to any kind of XML document, including SVG and XUL.

Advantages of CSS
Rich Styling - CSS allows for much richer document appearances than HTML ever allowed Style sheets can drastically reduce a web author's workload.

Ease of Use - style sheets centralize the commands for certain visual effects in one handy place, instead of scattering them throughout the document, so it's easier to type and change.

CSS is designed primarily to enable the separation of document content from document presentation, including elements such as the layout, colors, and fonts. This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics, enable multiple pages to share formatting, and reduce complexity and repetition in the structural content (such as by allowing for tableless web design).
CSS can allow the same markup page to be presented in different styles for different rendering methods, such as on-screen, in print, by voice and on Braille-based, tactile devices.
Readers still can use a different style sheet to override the one the author has specified.

CSS specifies a priority scheme to determine which style rules apply if more than one rule matches against a particular element. In this so-called cascade, priorities or weights are calculated and assigned to rules, so that the results are predictable.

Compact File Size - CSS can help keep document sizes as small as possible, thereby speeding download times.
Preparing for the Future - the W3C is beginning to remove stylistic elements from HTML.
Bringing CSS and XHTML Together
<link rel="stylesheet" type="text/css" href="sheet1.css" media="all" />
<style type="text/css">
@import url(sheet2.css);
h1 {color: maroon;}
</style>
Alternate style sheets
<link rel="alternate stylesheet" type="text/css" href="bigtext.css" title="Big Text" />
Inline Styles <p style="color: gray;">

It's important to understand various kinds of CSS selectors, CSS inheritance, and Cascading.
CSS selectors
Selectors are one of the most important aspects of CSS as they are used to "select" elements on an HTML page so that they can be styled.
Selectors
* Type selectors
* Class selectors
* ID selectors
* Descendant selectors
* Child selectors
* Universal selectors
* Adjacent sibling selectors
* Attribute selectors
* Pseudo-classes
* Pseudo-elements

Inheritance is the mechanism by which styles are applied not only to a specified element, but also to its descendants, CSS inheritance works on a property by property basis. When applied to an element in a document, a property with the value 'inherit' will use the same value as the parent element has for that property.


Resources:
CSS: The Definitive Guide
http://en.wikipedia.org/wiki/Cascading_Style_Sheets

Eclipse and Eclipse RCP

Eclipse and Eclipse RCP

Eclipse RCP is a platform for building and deploying rich client desktop applications. The rich means "rich" user experience, It provides high-quality end-user experience, native user interfaces, high-speed local processing, rich UIs support such as drag-and-drop, system clipboard, navigation, and customization.

An RCP application is a collection of plug-ins and a Runtime on which they run. An RCP developer assembles a collection of plug-ins from the Eclipse base and elsewhere and adds in the plug-ins he has written.

Eclipse RCP consists of the following components:
    * Core platform, runtime, lifecycle manager
    * Equinox OSGi – a standard OSGI bundling framework   
    * Standard Widget Toolkit (SWT) – a portable widget toolkit
    * JFace – viewer classes to bring model view controller programming to SWT, file buffers, text handling, and text editors
    * Eclipse Workbench – views, editors, perspectives, wizards
    * An update manager
Advantages of Eclipse RCP
Native look and feel - SWT
SWT uses native widgets as much as possible; this makes the look and feel of SWT-based applications match that of the host window system.
Eclipse plugin mechanism and Extensibility - OSGI
       Eclipse RCP applications are composed of a collection of existing plug-ins and plug-ins we developed, and applications can evolve over time by adding and replacing components.
Many available Eclipse components/Plugins for reuse
There are many other Eclipse components or plugins available for reuse (e.g. Help UI, Update Manager, Cheat Sheets, Intro, etc.), also many third-parties components.
Intelligent install and update
Due to OSGI, you can install, uninstall, start, and stop different modules of your application dynamically without restarting the container.
Disconnected operation
Development tooling support


Some History
For traditional desktop application, deploying and upgrading clients is a manual task, and need much time and money.
Then along came the Internet and Web-based applications, or thin clients.
Thin clients solved many of the deployment and management problems related to rich clients. Since applications were on servers, updates were made centrally. User machines required only a Web browser. This reduced the cost of deploying and maintaining enterprise applications at the expense of the user experience thin clients did not provide the UI features and high-speed interactions users had come to expect.
Thin client applications, using the request-and-response model, required more networking capability to ensure optimal interaction performance.

Standard Widget Toolkit (SWT)
SWT is a low-level graphics library that provides standard UI controls such as lists, menus, fonts, and colors. To display GUI elements, the SWT implementation accesses the native GUI libraries of the operating system using JNI
Pros and cons of SWT
Native look and feel
The real trick of SWT is to use native widgets as much as possible. This makes the look and feel of SWT-based applications match that of the host window system.

And to avoid the least-common-denominator approach that doomed AWT to mediocrity, SWT implements widgets in Java if no native counterpart exists on the target platform
Better Performance
Cons:
Swing is distributed with the JRE, to use SWT, application must add additional SWT libraries.

SWT is not available on all Java-supported platforms, though SWT has already supported almost all mainstream platforms.
There is also some evidence that the performance of SWT on platforms other than Windows is noticeably less efficient.
Since SWT uses a different native library for each platform, SWT developers may be exposed to platform specific bugs.
JFace
JFace is built on top of SWT, and provides classes for handling common UI programming tasks. It brings MVC programming to the SWT, and includes a whole range of UI toolkit components, from image, standard dialogs and wizards etc.

Whereas SWT provides access to the widgets as defined by the window system, JFace adds structure and facilities for common UI notions.
UI Workbench
As JFace adds structure to SWT, the Workbench adds presentation and coordination to JFace. To the user, the Workbench consists of views and editors arranged in a particular layout. In particular, the Workbench:
* Provides contribution-based UI extensibility
* Defines a powerful UI paradigm with windows, perspectives, views, editors, and actions

OSGI
The Eclipse plug-in component model is based on an implementation of the OSGi framework, OSGI defines architecture for modular application development, OSGi specification forms a framework for defining, composing, and executing components or bundles.
OSGi offers the following advantages:
    * Dynamic Updates, you can install, uninstall, start, and stop different modules of your application dynamically without restarting the container.
    * Your application can have more than one version of a particular module running at the same time, you can enable the version you want.
    * Reuse - The OSGi component model makes it very easy to use many third party components in an application. An increasing number of open source projects provide their JARs ready made for OSGi.
    * OSGi provides very good infrastructure for developing service-oriented applications, as well as embedded, mobile, and rich internet apps.

OSGi container implementations include Eclipse Equinox, Knopflerfish, and Apache Felix. Many web servers such as Apache geronimo, SpringSource dm Server, also in IBM WAS are built on OSGI.
Eclipse
Eclipse is a multi-language software development environment comprising an IDE and an extensible plug-in system. It also can be used to develop C, C++, COBOL, Python, Perl, PHP, and others.

Users can extend its capabilities by installing plug-ins written for the Eclipse software framework, such as development toolkits for other programming languages, and can write and contribute their own plug-in modules.

Resources:
Eclipse Rich Client Platform: Designing, Coding, and Packaging Java(TM) Applications
http://www.ibm.com/developerworks/websphere/techjournal/0608_xu/0608_xu.html
Hello, OSGi, Part 1: Bundles for beginners
http://www.osgi.org/About/WhyOSGi
http://en.wikipedia.org/wiki/Rich_Client_Platform

Java Web Services

Java Web Services

Web services are typically application programming interfaces (API) or web APIs that is executed on a remote system and can be accessed over a network.

Web services can be divided roughly into two groups, SOAP-based and REST-style.

Advantages of Web Services
Language transparency and Interoperability
Web services and their clients can interoperate even if written in different programming languages. Language transparency is the key to web service interoperability that is the ability of web services and requesters to interact seamlessly despite differences in programming languages, support libraries, and platforms.

Standard and Open infrastructure
Web services are deployed using industry-standard, vendor-independent protocols such as HTTP and XML, SOAP, WSDL, which are ubiquitous and well understood.

Modular design
Web services are meant to be modular in design so that new services can be generated through the integration and layering of existing services, this is the basic concepts of SOA.

Main components in web services include XML, SOAP, and WSAL.
WSDL
The Web Services Description Language is an XML-based language that provides a model for describing Web services.

A WSDL document is a contract between a service and its consumers. The contract provides such critical information as the service endpoint, the service operations, and the data types required for these operations.

SOAP
SOAP stands for as Simple Object Access Protocol, is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks.

It relies on XML as its message format, and usually relies on other Application Layer protocols (most notably HTTP and Remote Procedure Call (RPC)) for message negotiation and transmission.

In SOAP-based web services, the SOAP is mostly unseen infrastructure.

Web Services in Java
Java defines some APIs to support web services development such as JAX-WS, JAXP, and JAXB.

It is very easy to develop web services in Java EE5. After write web services interface, and implementation - POJO or EJB, we can just add annotation, @WebService, @WebMethod, @WebResult, @SOAPBinding, @WebServiceProvider(for Restful Web Service) to expose these operations as web services.

The Service Endpoint Interface and Service Implementation Bean
In A SOAP-based web service, there should be an interface that declares the methods, the interface is called the SEI: Service Endpoint Interface and an implementation, which implements the methods declared in the interface, the implementation is called the SIB: Service Implementation Bean.
The SIB can be either a POJO or a Stateless Session EJB.

Restful Web Service
REST stands for REpresentational State Transfer. Roy Fielding coined the acronym in his Ph.D. dissertation to describe an architectural style in the design of web services.

Jersey is reference implementation for building RESTful Web services.
WADL
WADL stands for Web Application Description Language.

WADL can be thought of as the REST equivalent of Web Services Description Language version 1.1. Version 2.0 of WSDL can be used to describe REST Web services, thus competing with WADL.

Resources:
Java Web Services: Up and Running
http://en.wikipedia.org/wiki/Web_service
http://en.wikipedia.org/wiki/SOAP

Taking Notes on Design Pattern

Taking Notes on Design Pattern

What is Design Patterns?
Design pattern describes a problem which occurs over and over again, and then describes the core of the solution to that problem.
Design patterns are a well-established mechanism for communicating best practices.
Why use Design Patterns?
Reuse solutions
Most problems we encounter as programmers have been handled time and again by others. Design patterns can provide us with the means to reuse their solution and wisdom.
We also learn from the experience of others enriches our language.
Establish a common base of vocabulary and terminology
Communication and teamwork require a common base of vocabulary and a common viewpoint of the problem. Design patterns provide a common point of reference during the analysis and design phase of a project.
Design patterns give a higher perspective on analysis and design
Patterns give you a higher-level perspective on the problem and on the process of design and object orientation.
This frees you from the tyranny of dealing with the details too early.
Design patterns helped both individual learning and team communications and development.
Creational Patterns
Factory pattern
It is used to take the rules of how to perform the instantiation out of the client object that is using these created objects.
Factory Method Pattern
Definition:
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to subclasses.
Participants
Product, ConcreteProduct, Factory, ConcreteFactory
Factory relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.
Abstract Factory Pattern
Definition:
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
The Abstract Factory is used when we must coordinate the creation of families of objects and each family is used under different circumstances.
The AbstractFactory defines the interface for how to create each member of the family of objects required.
We implement one concrete factory class for each family.
To create different types of product objects, clients should use a different concrete factory.
Consequences
A factory is responsible for creating product objects; it isolates clients from the task of creating product objects.
2. It makes exchanging product families easy.
3.  It promotes consistency among products. When product objects in a family are designed to work together, it's important that an application use objects from only one family at a time.
AbstractFactory makes this easy to enforce.  
4. Supporting new kinds of products is difficult, as this requires extending the factory interface and changing the AbstractFactory class and all of its subclasses.
Builder Pattern
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Applicability
Use the Builder pattern when
  the algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.  
  the construction process must allow different representations for the object that's constructed.  
Consequences
1. It lets you vary a product's internal representation. The Builder object provides the director with an abstract interface for constructing the product.
2. It isolates code for construction and representation. The Builder pattern improves modularity by encapsulating the way a complex object is constructed and represented.
3. It gives you finer control over the construction process. The Builder pattern constructs the product step by step under the director's control. This gives you finer control over the construction process and consequently the internal structure of the resulting product.
STRUCTURAL PATTERNS
Decorator
The Decorator Pattern is used to extend the functionality of an object dynamically without having to change the original class source or using inheritance. The key to a decorator is that a decorator "wraps" the object decorated and looks to a client exactly the same as the object wrapped. This means that the decorator implements the same interface as the object it decorates.
Participants
•Component - defines the interface for objects that can have responsibilities added to them dynamically.  
•ConcreteComponent - defines an object to which additional responsibilities can be attached.
•Decorator - maintains a reference to a Component object and defines an interface that conforms to Component's interface.
•ConcreteDecorator - adds responsibilities to the component. 
Decorator forwards requests to its Component object. It may optionally perform additional operations before and after forwarding the request. 
Decorator also implements Component interface, it can be treated as component, a decorator object can contain another decorator object and can forward calls to it. In this way, new decorators, and hence new functionality, can be built by wrapping an existing decorator object.
Benefits
More flexibility than static inheritance. The Decorator pattern provides a more flexible way to add responsibilities to objects than can be had with static inheritance. With decorators, responsibilities can be added and removed at run-time simply by attaching and detaching them. In contrast, inheritance requires creating a new class for each additional responsibility.
It is easy to add new component, and new decorator.
It is easy to add any combination of capabilities. The same capability can even be added twice.
I can prevent the proliferation of subclasses leading to less complexity and confusion.
Liabilities
Lots of little objects. A design that uses Decorator often results in systems composed of lots of little objects that all look alike.
Although these systems are easy to design, customize and extend, they can be hard to learn, use and debug.
Examples 1:
VisualComponent
TextView
Decorator
ScrollDecorator and BorderDecorator
Examples 2:
Logger
ConsoleLogger, FileLogger
LoggerDecorator
EncryptLogger
Decorator Pattern in java.io
InputStream, OutputStream(Byte)
Reader, Writer (Char)
Binary I/O streams (ascii, 8 bits)
InputStream
OutputStream
• Character I/O streams (Unicode, 16 bits)
Reader
Writer
Java filter streams (decorators) are added dynamically to create the functionality needed.
Input decorator: FilterInputStream
Output decorator: FilterOutputStream
InputStream Hierarchy
• Abstract component root in decorator pattern - InputStream
• Concrete components
FileInputStream, ByteArrayInputStream, StringBufferInputStream, PipedInputStream
• Abstract decorator - FilterInputStream
• Concrete decorators
DataInputStream, BufferedInputStream, LineNumberInputStream, PushbackInputStream, etc.
DataInputStream in = new DataInputStream(new BufferedInputStream (new FileInputStream("invoice1.txt")));
OutputStream Hierarchy
• Abstract component root in decorator pattern – OutputStream
• Concrete components
FileOutputStream, ByteArrayOutputStream, PipedOutputStream
• Abstract decorator –FilterOutputStream
• Concrete decorators
DataOutputStream,PrintStream, BufferedOutputStream
DataOutputStream out = new DataOutputStream(new BufferedOutputStream( new FileOutputStream("invoice1.txt")));
Reader and Writer Classes
Internationalization Unicode support
Structured in class hierarchies similar to the InputStream and OutputStream hierarchies
Reader Class Hierarchy
• Abstract component root in decorator pattern –Reader
• Concrete components – BufferedReader
• Abstract decorator –FilterReader
• Concrete decorators – PushbackReader
ADAPTER Pattern
Adapter pattern can convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Sometimes, an existing class may provide the functionality required by a client, but its interface may not be what the client expects. In such cases, to reuse the existing class, the existing interface needs to be converted into another interface, which the client expects.
The Adapter pattern suggests defining a wrapper class around the object with the incompatible interface. This wrapper object is referred as an adapter and the object it wraps is referred to as an adaptee. The adapter provides the required interface expected by the client. The implementation of the adapter interface converts client requests into calls to the adaptee class interface.
Applicability
Use the Adapter pattern when you want to use an existing class, and its interface does not match the one you need.  
CLASS ADAPTERS VERSUS OBJECT ADAPTERS
Adapters can be classified broadly into two categories - class adapters and object adapters - based on the way a given adapter is designed.
Class Adapter
A class adapter is designed by sub classing the adaptee class. In addition, a class adapter implements the interface expected by the client object. When a client object invokes a class adapter method, the adapter internally calls an adaptee method that it inherited.
Object Adapter
An object adapter contains a reference to an adaptee object. Similar to a class adapter, an object adapter also implements the interface, which the client expects.
When a client object calls an object adapter method, the object adapter invokes an appropriate method on the adaptee instance whose reference it contains.
Clients call operations on an Adapter instance. In turn, the adapter calls Adaptee operations that carry out the request.
Adapter can only change the names of operations, or support an entirely different set of operations. The amount of work Adapter does depends on how similar the Target interface is to Adaptee's. 
Example:
AddressValidator{isValidAddress}
CAAddressValidator{isValidCanadianAddr}
Iteration to Enumeration
Enumeration to Iteration
Adapter Pattern in Java IO
ByteArrayInputStream, encapsulate array, and convert it to InputStream.
FileInputStream(FileDescriptor to InputStream)
StringBufferInputStream(String to InputStream)
ByteArrayOutputStream, FileOutputStream
CharArrayReader, StringReader,
CharArrayWriter, StringWriter
Byte to Char
InputStreamReader
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.
Convert InputStream to Reader
OutputStreamWriter
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.
InputStreamReader isr = new InputStreamReader(new FileInputStream(new File("a.txt")));
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
Observer Pattern
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The key objects in this pattern are subject and observer.
A subject may have any number of dependent observers. All observers are notified whenever the subject undergoes a change in state. In response, each observer will query the subject to synchronize its state with the subject's state.
This kind of interaction is also known as publish-subscribe. The subject is the publisher of notifications. It sends out these notifications without having to know who its observers are. Any number of observers can subscribe to receive notifications.
After applying the Observer pattern, different observers can be added dynamically without requiring any changes to the Subject class.
Applicability
Use the Observer pattern in any of the following situations:
• When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
• When a change to one object requires changing others, and you don't know how many objects need to be changed.  
• When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.  
Participants
• Subject - knows its observers. Any number of Observer objects may observe a subject, provides an interface for attaching and detaching Observer objects.  
• Observer - defines an updating interface for objects that should be notified of changes in a subject.
• ConcreteSubject - stores state of interest to ConcreteObserver objects, sends a notification to its observers when its state changes.
• ConcreteObserver - maintains a reference to a ConcreteSubject object, stores state that should stay consistent with the subject's, implements the Observer updating interface to keep its state consistent with the subject's.
Collaborations
• ConcreteSubject notifies its observers whenever a change occurs that could make its observers' state inconsistent with its own.  
• After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for information. ConcreteObserver uses this information to reconcile its state with that of the subject.
Consequences
1. Abstract coupling between Subject and Observer. All a subject knows is that it has a list of observers, each conforming to the simple interface of the abstract Observer class. The subject doesn't know the concrete class of any observer. Thus the coupling between subjects and observers is abstract and minimal.   
2. Support for broadcast communication.
The notification is broadcast automatically to all interested objects that subscribed to it.
3. Unexpected updates.
Observer in Java
Interface: Observer
Observable Class - setChaged, and notifyObservers methods.
Remember to call setChaged() method before notifyObservers, otherwise, will not notify changes to observers.
Example:
IndexPaser, PackageParser, ClassPaser.
Command Pattern
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Command pattern turns the request itself into an object. This object can be stored and passed around like other objects.
Applicability
• Specify, queue, and execute requests at different times.
• Support undo.
Participants
• Command - declares an interface for executing an operation.
• ConcreteCommand - defines a binding between a Receiver object and an action, implements Execute by invoking the corresponding operation(s) on Receiver.
• Client - creates a ConcreteCommand object and sets its receiver.
• Invoker - asks the command to carry out the request.  
• Receiver - knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver.  
Consequences
The Command pattern has the following consequences:
1. Command decouples the object that invokes the operation from the one that knows how to perform it.
2. Commands are first-class objects. They can be manipulated and extended like any other object.
3. You can assemble commands into a composite command.
4. It’s easy to add new Commands.
Example:
PlayBox, Keypad,
Command, Start/Stop/PlayCommand
MacroCommand
Behavioral Patterns
Chain of Responsibility
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
The request gets passed along a chain of objects until one of them handles it.
It decouples an object that sends out a request and the set of potential request handler objects.
Applicability
Use Chain of Responsibility when
• More than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically.  
• You want to issue a request to one of several objects without specifying the receiver explicitly.  
• The set of objects that can handle a request should be specified dynamically.
Consequences
1.  Reduced coupling
2.  Added flexibility in assigning responsibilities to objects.
3.  Receipt isn't guaranteed.
Example:
PurchaseRequest
PRHandler
BranchManager,RegionalDirector,PresidentCOO,VicePresident
Event Mode in DHTML
Java web Filter
Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Participants
•  Strategy - declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.
•  ConcreteStrategy - implements the algorithm using the Strategy interface.
•  Context - is configured with a ConcreteStrategy object, maintains a reference to a Strategy object, may define an interface that lets Strategy access its data.
Consequences
The Strategy pattern has the following benefits and drawbacks:
1.  Families of related algorithms.
3.  Strategies eliminate conditional statements.
Template Method
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
A template method defines an algorithm in terms of abstract operations that subclasses must override to provide concrete behavior.
Applicability
The Template Method pattern should be used
• To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.
• When common behavior among subclasses should be factored and localized in a common class to avoid code duplication.
Template methods are a fundamental technique for code reuse.
Example:
Reporter.generateReport
HTMLRepoter/ClassHTLReporter
Visitor Pattern
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Applicability
Use the Visitor pattern when
• An object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.  
• Many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them.  
Participants
• Visitor (visit) - declares a Visit operation for each class of ConcreteElement in the object structure.
•  Concrete Visitor (TypeCheckingVisitor)
•  Element (accept) - defines an Accept operation that takes a visitor as an argument.
•  ConcreteElement (AssignmentNode,VariableRefNode) - implements an Accept operation that takes a visitor as an argument.
•  ObjectStructure (Program) - can enumerate its elements, may provide a high-level interface to allow the visitor to visit its elements,  may either be a composite (see Composite (163)) or a collection such as a list or a set.  
Consequences
1.  Visitor makes adding new operations easy.
2.  A visitor gathers related operations and separates unrelated ones
3.  Adding new ConcreteElement classes is hard. The Visitor pattern makes it hard to add new subclasses of Element
4.  Visiting across class hierarchies, it can visit objects that don't have a common parent class. You can add any type of object to a Visitor interface.
Accumulating state.
Breaking encapsulation.
Example 1:
Element/ElementA/CompositeElement
Visitor/ConcreteVisitor
Example 2:
Visitor/PriceVisitor/InventoryVisitor(visitHardDisk, visitCPU...)
Equipment/HardDisk/CPU(accept)
Iterator Pattern
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
The Iterator pattern allows a client object to access the contents of a container in a sequential manner, without having any knowledge about the internal representation of its contents.
The Iterator class defines an interface for accessing the list's elements. An iterator object is responsible for keeping track of the current element.
Separating the traversal mechanism from the List object lets us define iterators for different traversal policies without enumerating them in the List interface
The key idea in this pattern is to take the responsibility for access and traversal out of the list object and put it into an iterator object.
Applicability
Use the Iterator pattern
•  to access an aggregate object's contents without exposing its internal representation. 
•  to support multiple traversals of aggregate objects.
•  to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).  
Participants
•  Iterator - defines an interface for accessing and traversing elements.
•  ConcreteIterator - implements the Iterator interface, keeps track of the current position in the traversal of the aggregate. 
•  Aggregate - defines an interface for creating an Iterator object.  
•  ConcreteAggregate - implements the Iterator creation interface to return an instance of the proper ConcreteIterator.  
1.  It supports variations in the traversal of an aggregate.
2.  Iterators simplify the Aggregate interface.
3.  More than one traversal can be pending on an aggregate.
1.  Who controls the iteration?
When the client controls the iteration, the iterator is called an external iterator, and when the iterator controls it, the iterator is an internal iterator.
Internal iterators
– The collection itself offers methods to allow a client to visit different objects within the collection. For example, the java.util.Result-Set
– There can be only one iterator on a collection at any given time.
– The collection has to maintain or save the state of iteration.
External iterators
– The iteration functionality is separated from the collection and kept inside a different object referred to as an  iterator. Usually, the collection itself returns an appropriate iterator object to the client depending on the client input.
– There can be multiple iterators on a given collection at any given time.
Usage in Java
Enumeration
Iterator/ListIterator[add,remove,set,previous,next]
AbstractList, Inner class, Itr,ListItr
Fail fast, ConcurrentModificationException

Resources:

OOP in JavaScript

Object Oriented Programming in JavaScript

There are no classes in JavaScript. Functions can be used to somewhat simulate classes.
We can define instance properties, instance methods, and class properties, class methods, we can also use prototype to define inheritance.
In JavaScript, it's important to understand concept of execution context, search order, prototype.
Creating Objects
The simplest way to create a custom object is to create a new instance of Object and add properties and methods to it:
var person = new Object();
person.name = "Nicholas";
person.sayName = function(){ alert(this.name); };
The downside to this approach is that creating multiple objects with the same interface requires a lot of code duplication.
The Constructor Pattern
function Person(name, age, job){
    this.name = name; …
    this.sayName = function(){ alert(this.name);};   
}
Problems with Constructors
The major downside to constructors is that methods are created once for each instance and those instances' methods are not the same instance of Function.
The Prototype Pattern
The benefit of using the prototype is that all of its properties and methods are shared among object instances.
function Person(){}
Person.prototype.name = "Nicholas";
Person.prototype.sayName = function(){ alert(this.name); };
Alternate Prototype Syntax
Instead of adding to the prototype object, another way to achieve the above result is to overwrite the prototype completely.
Person.prototype = {
    constructor: Person,
    name : "Nicholas", …
    sayName : function () { alert(this.name); }
};
Problems with Prototypes
Prototype negates the ability to pass initialization arguments into the constructor. All properties on the prototype are shared among instances, this is ideal for functions, but problem occurs when a property contains a reference value.
Combination Constructor/Prototype Pattern
The most common way of defining custom types is to combine the constructor and prototype patterns. The constructor pattern defines instance properties, whereas the prototype pattern defines methods and shared property.
function Person(name, age, job){ this.name = name; }
Person.prototype = {
    constructor: Person,
    sayName : function () { alert(this.name); }
};
We can also enhance built-in objects, such as arrays or strings
Inheritance
Prototype Chaining
The basic idea is to use the concept of prototypes to inherit properties and methods between two reference types.
function SuperType(){}
function SubType(){}
SubType.prototype = new SuperType();//inherit from SuperType
SubType.prototype.getSubValue = function (){}; //new method
SubType.prototype.getSuperValue = function (){};  //override existing method
Problems with Prototype Chaining
The major issue revolves around prototypes that contain reference values. When implementing inheritance using prototypes, the prototype actually becomes an instance of another type, meaning that what once were instance properties are now prototype properties.
A second issue with prototype chaining is that you cannot pass arguments into the supertype constructor when the subtype instance is being created.
Constructor Stealing
The basic idea is quite simple: call the supertype constructor from within the subtype constructor.
function SuperType(name){ this.name = name;}
function SubType(){     
SuperType.call(this, “Nicholas”);
this.age = 29; //instance property
}
By using the call () method (or alternately, apply ()), the SuperType constructor is called in the context of the newly created instance of SubType. Doing this effectively runs all of the object-initialization code in the SuperType() function on the new SubType object. The result is that each instance has its own copy of the colors property.
Problems with Constructor Stealing
The downside to using constructor stealing is that:  methods must be defined inside the constructor, so there’s no function reuse.
Combination Prototype Chaining and Constructor Stealing
The basic idea is to use prototype chaining to inherit properties and methods on the prototype, and to use constructor stealing to inherit instance properties. This allows function reuse by defining methods on the prototype and allows each instance to have its own properties.
function SuperType(name){ this.name = name; }
function SubType(name, age){ 
    SuperType.call(this, name); //inherit properties
    this.age = age;
}
SubType.prototype = new SuperType();//inherit methods
SubType.prototype.sayAge = function(){};
Problems with Combination Inheritance
The most inefficient part of the pattern is that the supertype constructor is always called twice: once to create the subtype’s prototype, and once inside the subtype constructor.
Browser Object Model
The Browser Object Model (BOM) provides objects that expose browser functionality independent of any web page content, and provides objects, such as window, location, navigator, screen, and history.
Document Object Model
The DOM represents a document as a hierarchical tree of nodes, allowing        developers to add, remove, and modify individual parts of the page.

Resources:

Labels

Java (159) Lucene-Solr (110) Interview (59) All (58) J2SE (53) Algorithm (45) Soft Skills (36) Eclipse (34) Code Example (31) Linux (24) JavaScript (23) Spring (22) Windows (22) Web Development (20) Nutch2 (18) Tools (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) Troubleshooting (9) UIMA (9) html (9) Http Client (8) Maven (8) Security (8) bat (8) blogger (8) Big Data (7) Continuous Integration (7) Google (7) Guava (7) JSON (7) Problem Solving (7) ANT (6) Coding Skills (6) Database (6) Dynamic Languages (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) IDE (5) Lesson Learned (5) Programmer Skills (5) System Design (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Firefox (2) Google Drive (2) Gson (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Python (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts