Sunteți pe pagina 1din 8

Java Revision Observer Design Pattern

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. The objects which are watching the state changes are called observer. Alternatively observer are also called listener. The object which is being watched is called subject.

Example
View A is the subject. View A displays the temperature of a container. View B display a green light is the temperature is above 20 degree Celsius. Therefore View B registers itself as a Listener to View A. If the temperature of View A is changed an event is triggered. That is event is send to all registered listeners in this example View B. View B receives the changed data and can adjust his display.

Evaluation
The observer pattern allow for Open Closed Principle. The subject can registered an unlimited number of observers. If a new listener should register at the subject no code change in the subject is necessary. The subject and the observer are loosely coupled. If a controller is used then neither the subject nor the observer have direct knowledge about each other. If no controller is used then only the observer has a knowledge about the subject.

Comparable Vs Comparator Interface Comparable: public int compareTo (Object o); Comparator: public int compare (Type t1, Type t2);

Spring Parameter ambiguity: use type and index attributes. Ref attribute to inject bean into bean. Property collection is like a map, but the keys and values are both strings.

Wrappers Converting a primitive to wrapper object in called boxing. Converting a wrapper object to a primitive is called unboxing. Java automatically boxes primitives and unboxes wrapper objects. This is called autoboxing and autounboxing.

Autowiring Mode no byName

Description No autowiring is performed. All references to other beans must be explicitly injected. This is the default mode. Based on the name of a property, a matching bean name in the IoC container will be injected into this property if it exists. Based on the type of class on a setter, if only one instance of the class exists in the IoC container it will be injected into this property. If there is more than one instance of the class a fatal exception is thrown. Based on a constructor argument's class types, if only one instance of the class exists in the IoC container it will be used in the constructor. If there is a valid constructor, the constructor autowiring mode will be chosen. Otherwise if there is a default zero argument constructor the byType autowiring mode will be chosen.

byType

constructor

autodetect

Difference between prototype and singleton Singleton only one per bean.

<bean id="namexBean" class="com.namex.spring.NamexBean" scope="prototype" />

Session tracking Cookies SSL sessions URL Rewriting

Hash Code Equals Person{ String name; int age;

String hashCode(String age){ return name.hashCode() + age; }

equals(Object o){ if(o instanceOf Person) return false; Person p = (Person) o;

equals() (javadoc) must define an equality relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false. hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value). The relation between the two methods is: Whenever a.equals(b), then a.hashCode() must be same as b.hashCode(). In practice: If you override one, then you should override the other. Use the same set of fields that you use to compute equals() to compute hashCode(). Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example: public class Person { private String name; private int age; // ... public int hashCode() { return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers // if deriving: appendSuper(super.hashCode()). append(name). append(age). toHashCode(); } public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj.getClass() != getClass()) return false; Person rhs = (Person) obj; return new EqualsBuilder(). // if deriving: appendSuper(super.equals(obj)). append(name, rhs.name). append(age, rhs.age). isEquals(); } }

Also remember: When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.

Differences between Overloaded and Overridden Methods: Overloaded Methods Arguments Must Change Return Can Change Type Access Can Change Overridden Methods Must Not Change Cannot Change (Except for Covariant Returns) Cannot Change to more restrictive (Can be less restrictive) Object type (in other words, the type of the actual instance on the heap) determines which method is selected. Happens at runtime.

Reference type determines which overloaded version (based on declared argument types) is selected. Happens at compile time. The actual method thats invoked is still a virtual method invocation that Invocation happens at runtime, but the compiler will already know the signature of the method to be invoked. So at runtime, the argument match will already have been nailed down, just not the class in which the method lives.

What Is Stack? Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the thread. A Java virtual machine stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Because the Java virtual machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated. The memory for a Java virtual machine stack does not need to be contiguous. The Java virtual machine specification permits Java virtual machine stacks either to be of a fixed size or to dynamically expand and contract as required by the computation. If the Java virtual machine stacks are of a fixed size, the size of each Java virtual machine stack may be chosen independently when that stack is created. A Java virtual machine implementation may provide the programmer or the user control over the initial size of Java virtual machine stacks, as well as, in the case of dynamically expanding or contracting Java virtual machine stacks, control over the maximum and minimum sizes. The following exceptional conditions are associated with Java virtual machine stacks:

If the computation in a thread requires a larger Java virtual machine stack than is permitted, the Java virtual machine throws a StackOverflowError. If Java virtual machine stacks can be dynamically expanded, and expansion is attempted but insufficient memory can be made available to effect the expansion, or if insufficient memory can be made available to create the initial Java virtual machine stack for a new thread, the Java virtual machine throws an OutOfMemoryError

What Is Heap? The Java virtual machine has a heap that is shared among all Java virtual machine threads. The heap is the runtime data area from which memory for all class instances and arrays is allocated. The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java virtual machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementors system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous. The heap mainly store objects create using or class level variables. The following exceptional condition is associated with the heap:

If a computation requires more heap than can be made available by the automatic storage management system, the Java virtual machine throws an OutOfMemoryError

Use Comparable if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this. if the object is in your control if the comparing behaviour if the the main comparing behaviour

Use Comparator if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour if the object is outside your control and you cannot make them implement Comparable when you want comparing behaviour different from the default (which is specified by Comparable)

So in Summary if you want to sort based on natural order or object then use Comparable in Java and if you want to sort on some other attribute of object then Comparator in Java is the way to go. Now to understand these concepts lets see an example 1) There is class called Person, sort the Person based on person_id. 2) Sort the Person based on Name. For a Person class sorting based on person_id can be treated as natural order sorting and sorting based on Name can be implemented using Comparator interface. To sort based on person_id we need to implement compareTo() method.

public class Person implements Comparable { private int person_id; private String name; /** * Compare current person with specified person * return zero if person_id for both person is same * return negative if current person_id is less than specified one * return positive if specified person_id is greater than specified one */ public int compareTo(Person o) { return this.person_id - o.person_id ; } .

And for sorting based on person name we can implement compare (Object o1, Object o2) method of Comparator in Java or Java Comparator class. public class PersonSortByPerson_ID implements Comparator{ public int compare(Person o1, Person o2) { return o1.getPersonId() - o2.getPersonId(); }

You can write several types of Java Comparator based upon your need for example reverseComparator , ANDComparator , ORComparator etc which will return negative or positive number based upon logical results.

Difference between Comparator and Comparable in Java


1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package. 2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. 3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified. 4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface. 5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method. 6)Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.

Q: What are the common mechanisms used for session tracking? A: Cookies SSL- sessions URL- rewriting Hidden Fields Q: Explain ServletContext. A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

ServletContext(): To communicate with the Servlet Container. Eg: What server to running on the Environment.Then when sever is started,who is login the server all the information to store the "Event log"file ie log4j. ServletConfig(): Pass the configuration information to the Server to the servlet. Session(): Session is a Object to track the user interaction with the web application across multiple HttpSessions.

S-ar putea să vă placă și