Design Patterns
239 pág.

Design Patterns


DisciplinaEngenharia de Software I5.636 materiais57.596 seguidores
Pré-visualização50 páginas
Fruit 
getFruitByTypeNameHighConcurrentVersion(FRUIT_TYPE type) {
 if (!types.containsKey(type)) {
 synchronized (types) {
 // Check again, after having acquired the lock 
to make sure
 // the instance was not created meanwhile by 
another thread
 if (!types.containsKey(type)) {
 // Lazy initialisation
Lazy initialization 45
 types.put(type, new Fruit(type));
 }
 }
 }
 
 return types.get(type);
 }
 
 /**
 * Displays all entered fruits.
 */
 public static void showAll() {
 if (types.size() > 0) {
 System.out.println("Number of instances made = " + 
types.size());
 
 for (Entry<FRUIT_TYPE, Fruit> entry : types.entrySet()) {
 System.out.println(
 
Constants.firstLetterToUpper(entry.getKey().toString()));
 }
 
 System.out.println();
 }
 }
}
Output
Number of instances made = 1
Banana
Number of instances made = 2
Banana
Apple
Number of instances made = 2
Banana
Apple
JavaScript
Here is an example in JavaScript.
var Fruit = (function() {
 var types = {};
 function Fruit() {};
 // count own properties in object
 function count(obj) {
Lazy initialization 46
 var i = 0;
 for (var key in obj) {
 if (obj.hasOwnProperty(key)) {
 ++i;
 }
 }
 return i;
 }
 var _static = {
 getFruit: function(type) {
 if (typeof types[type] == 'undefined') {
 types[type] = new Fruit;
 }
 return types[type];
 },
 printCurrentTypes: function () {
 console.log('Number of instances made: ' + count(types));
 for (var type in types) {
 console.log(type);
 }
 }
 };
 return _static;
})();
Fruit.getFruit('Apple');
Fruit.printCurrentTypes();
Fruit.getFruit('Banana');
Fruit.printCurrentTypes();
Fruit.getFruit('Apple');
Fruit.printCurrentTypes();
Output
Number of instances made: 1
Apple
Number of instances made: 2
Apple
Banana
Number of instances made: 2
Apple
Banana
Lazy initialization 47
PHP
Here is an example of lazy initialization in PHP 5:
<?php
header('Content-type:text/plain; charset=utf-8');
class Fruit {
 private $type;
 private static $types = array();
 private function __construct($type) {
 $this->type = $type;
 }
 public static function getFruit($type) {
 // Lazy initialization takes place here
 if (!array_key_exists($type, self::$types)) {
 return self::$types[$type] = new Fruit($type);
 }
 return self::$types[$type];
 }
 public static function printCurrentTypes() {
 echo 'Number of instances made: ' . count(self::$types) . &quot;\n&quot;;
 foreach (array_keys(self::$types) as $key) {
 echo &quot;$key\n&quot;;
 }
 echo &quot;\n&quot;;
 }
}
Fruit::getFruit('Apple');
Fruit::printCurrentTypes();
Fruit::getFruit('Banana');
Fruit::printCurrentTypes();
Fruit::getFruit('Apple');
Fruit::printCurrentTypes();
/*
OUTPUT:
Number of instances made: 1
Apple
Number of instances made: 2
Lazy initialization 48
Apple
Banana
Number of instances made: 2
Apple
Banana
*/
?>
Python
Here is an example in Python.
class Fruit:
 def __init__(self, sort):
 self.sort = sort
 
class Fruits:
 def __init__(self):
 self.sorts = {}
 
 def get_fruit(self, sort):
 if sort not in self.sorts:
 self.sorts[sort] = Fruit(sort)
 
 return self.sorts[sort]
if __name__ == '__main__':
 fruits = Fruits()
 print fruits.get_fruit('Apple')
 print fruits.get_fruit('Lime')
Ruby
Here is an example in Ruby, of lazily initializing an authentication token from a remote service like Google. The
way that @auth_token is cached is also an example of memoization.
require 'net/http'
class Blogger
 def auth_token
 @auth_token ||=
 (res = Net::HTTP.post_form(uri, params)) &&
 get_token_from_http_response(res)
 end
 # get_token_from_http_response, uri and params are defined later in 
the class
end
Lazy initialization 49
b = Blogger.new
b.instance_variable_get(:@auth_token) # returns nil
b.auth_token # returns token
b.instance_variable_get(:@auth_token) # returns token
Smalltalk
Here is an example in Smalltalk, of a typical accessor method to return the value of a variable using lazy
initialization.
 height
 ^height ifNil: [height := 2.0].
The 'non-lazy' alternative is to use an initialization method that is run when the object is created and then use a
simpler accessor method to fetch the value.
 initialize
 height := 2.0
 height
 ^height
Note that lazy initialization can also be used in non-object-oriented languages.
References
External links
\u2022 Article &quot; Java Tip 67: Lazy instantiation (http:/ / www. javaworld. com/ javaworld/ javatips/ jw-javatip67. html) -
Balancing performance and resource usage&quot; by Philip Bishop and Nigel Warren
\u2022 Java code examples (http:/ / javapractices. com/ Topic34. cjp)
\u2022 Use Lazy Initialization to Conserve Resources (http:/ / devx. com/ tips/ Tip/ 18007)
\u2022 Description from the Portland Pattern Repository (http:/ / c2. com/ cgi/ wiki?LazyInitialization)
\u2022 Lazy Initialization of Application Server Services (http:/ / weblogs. java. net/ blog/ binod/ archive/ 2005/ 09/
lazy_initializa. html)
\u2022 Lazy Inheritance in JavaScript (http:/ / sourceforge. net/ projects/ jsiner)
\u2022 Lazy Inheritance in C# (http:/ / labs. kaliko. com/ 2011/ 04/ lazy-loading-in-c-net. html)
Multiton pattern 50
Multiton pattern
In software engineering, the multiton pattern is a design pattern similar to the singleton, which allows only one
instance of a class to be created. The multiton pattern expands on the singleton concept to manage a map of named
instances as key-value pairs.
Rather than have a single instance per application (e.g. the java.lang.Runtime object in the Java
programming language) the multiton pattern instead ensures a single instance per key.
Most people and textbooks consider this a singleton pattern. For example, multiton does not explicitly appear in the
highly regarded object-oriented programming text book Design Patterns (it appears as a more flexible approach
named registry of singletons).
Example
An example thread-safe Java implementation follows:
Java
The first example synchronizes the whole getInstance() method (which may be expensive in a highly
concurrent environment).
 public class FooMultiton {
 private static final Map<Object, FooMultiton> instances = new HashMap<Object, FooMultiton>();
 
 private FooMultiton() /* also acceptable: protected, {default} 
*/ {
 /* no explicit implementation */
 }
 
 public static FooMultiton getInstance(Object key) {
 synchronized (instances) {
 
 // Our &quot;per key&quot; singleton
 FooMultiton instance = instances.get(key);
 
 if (instance == null) {
 
 // Lazily create instance
 instance = new FooMultiton();
 
 // Add