Matcher vs Pattern
Pattern: A compiled representation of a regular expression.Matcher: An engine that performs match operations on a character sequence by interpreting a Pattern.
A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern. A typical invocation sequence is thus
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
A matches method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement boolean b = Pattern.matches("a*b", "aaaaab");
is equivalent to the three statements above, though for repeated matches it is less efficient since it does not allow the compiled pattern to be reused. Instances of this
class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.
Immutable Object
An object is considered immutable if its state cannot change after it is constructed. Immutable objects are very useful in multithreaded applications because they can be shared between threads without synchronization. To create an immutable object you need to follow some simple rules:- Declare the class as final so it can’t be extended.
- Make all fields private final so that direct access is not allowed and assigned only once
- Don’t provide setter methods for variables
- Initialize all the fields via a constructor performing deep copy.
- Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
Comments
Post a Comment