Leniwe inicjowaniewzorzec projektowy polegający na opóźnianiu tworzenia obiektu, obliczania wartości lub przeprowadzania innych kosztownych operacji, aż do momentu pierwszego zapotrzebowania na nie.

Jest to zwykle dokonywane przez utrzymywanie flagi wskazującej, czy operacja (np. tworzenie obiektu) miała miejsce. Za każdym razem, gdy potrzebny jest wynik operacji, flaga jest testowana. Jeśli flaga wskazuje, że dana operacja miała już miejsce, to jest zwracany wynik operacji. Jeśli jeszcze nie, to wtedy dokonuje się tej operacji i zachowuje wynik.

"Leniwa fabryka"

edytuj

Często we wzorcach projektowych leniwe inicjowanie jest stosowane razem ze wzorcem metody fabrykującej. Taka kombinacja zespala ze sobą trzy idee:

  • Użycie metody fabrykującej do otrzymywania instancji klasy (metoda fabrykująca),
  • Przechowywanie instancji w mapie tak, że dostaje się za każdym razem tę samą instancję dla tych samych parametrów. Różni się od wzorca singletonu mnogością różnych instancji i uzależnieniem zwracanej instancji od parametrów – w singletonie jest jedna instancja i brak parametrów,
  • Używanie leniwego inicjowania do tworzenia instancji obiektu za pierwszym razem, gdy jest potrzebny (wzorzec leniwego inicjowania)(porównaj z wzorcem singletonu).

Przykłady

edytuj

Java

edytuj

Tu jest bardzo prosty przykład napisany w Javie. Klasa Fruit nic nie robi, po prostu stanowi przykład implementacji wzorca. Zmienna klasowa types jest mapą używaną do przechowywania instancji Fruit według typów.

import java.util.*;

public class Fruit
{
    private static final Map<String,Fruit>types = new HashMap<String,Fruit>();
    private final String type;

    // using a private constructor to force use of the factory method.
    private Fruit(String type) {
      this.type = type;
    }

    /**
     * Lazy Factory method, gets the Fruit instance associated with a
     * certain type. Instantiates new ones as needed.
     * @param type Any string that describes a fruit type, e.g. "apple"
     * @return The Fruit instance associated with that type.
     */
    public static synchronized Fruit getFruit(String type) {
      Fruit f = types.get(type); // get the instance for that type

      if (f == null) {
        f = new Fruit(type); // lazy initialization
        types.put(type,f);
      }

      return f;
    }
}

C++

edytuj

Przykład klasy Fruit napisanej w C++

#include <iostream>
#include <string>
#include <map>

using namespace std;

class Fruit {
    private:
        static map<string,Fruit*> types;
        string type;

        // note: constructor private forcing one to use static getFruit()
        Fruit(const string& t) : type( t ) {}

    public:
        static Fruit* getFruit(const string& type);
        static void printCurrentTypes();
};

//declaration needed for using any static member variable
map<string,Fruit*> Fruit::types;

/*
 * Lazy Factory method, gets the Fruit instance associated with a
 * certain type. Instantiates new ones as needed.
 * precondition: type. Any string that describes a fruit type, e.g. "apple"
 * postcondition: The Fruit instance associated with that type.
 */
Fruit* Fruit::getFruit(const string& type) {
    map<string,Fruit*>::iterator iter = types.find(type);   //try to find a pre-existing instance

    if (iter == types.end()) {
        // couldn't find one, so make a new instance
        Fruit* f = new Fruit(type); // lazy initialization part
        types[type] = f;
        return f;
    }
    else {
        return iter->second;
    }
}

/*
 * For example purposes to see pattern in action
 */
void Fruit::printCurrentTypes() {
    if (types.size() > 0) {
        cout << "Number of instances made = " << types.size() << endl;
        for (map<string,Fruit*>::iterator iter = types.begin(); iter != types.end(); ++iter) {
            cout << (*iter).first << endl;
        }
        cout << endl;
    }
}

int main(void) {
    Fruit::getFruit("Banana");
    Fruit::printCurrentTypes();

    Fruit::getFruit("Apple");
    Fruit::printCurrentTypes();

    // returns pre-existing instance from first
    // time Fruit with "Banana" was created
    Fruit::getFruit("Banana");
    Fruit::printCurrentTypes();

    return 0;
}
/*
OUTPUT:
Number of instances made = 1
Banana

Number of instances made = 2
Apple
Banana

Number of instances made = 2
Apple
Banana
*/

SmallTalk

edytuj

Poniżej jest przykład napisany w języku Smalltalk, używający metody dostępowej do zwracania wartości zmiennej przy pomocy leniwego inicjowania.

    height
        height ifNil: [height := 2.0].
        ^height

Alternatywą jest "nieleniwe" inicjowanie, które polega na użyciu inicjującej metody przy tworzeniu obiektu i wykorzystaniu metody dostępowej do pobierania wartości.

    initialize
        height := 2.0

    height
        ^height

Warto zauważyć, że leniwe inicjowanie może być też używane w nieobiektowych językach programowania.

Ruby

edytuj

Poniżej jest przykład napisany w języku Ruby:

require 'net/http'
class Blogger
  def auth_token
    @auth_token ||= get_token_from_http_response(Net::HTTP.post_form(uri, params))
  end

  # get_token_from_http_response, uri and params are defined later in the class
end

b = Blogger.new
b.instance_variable_get(:@auth_token) # returns nil
b.auth_token # returns token
b.instance_variable_get(:@auth_token) # returns token

Zobacz też

edytuj

Linki zewnętrzne

edytuj

📚 Artikel Terkait di Wikipedia

Hotsumi Ozaki

ISBN 0-8223-2519-5. [dostęp 2011-04-28]. (ang.). Johnson, Chalmers. An Instance of Treason Ozaki Hotsumi and the Sorge Spy Ring. Stanford CA: Stanford

HTML

2016-04-02] . TimT. Berners-Lee TimT., DanielD. Connolly DanielD., A sample HTML instance [online], www.w3.org, czerwiec 1993 [dostęp 2016-11-12] . DaveD. Raggett DaveD

Pismo automatyczne

1919–1935, Jemma Montagu Lily Dale Museum Joe Nickell: Abraham Lincoln: An Instance of Alleged 'Spirit Writing'. csicop.org, September 2004. [dostęp 2018-04-25]

Malleus Maleficarum

cautionary advice of the Spanish Inquisition in 1538 was merely another instance of the kinds of interest, and objections, that the Malleus raised." Młot

Baybayin

Benito Miguel D. Flores, IV, Macario O. Cordel, II: Baybayin Character Instance Detection. New York: Proceedings of Philippine Computing Society Conference

XHTML

atrybut schemaLocation z przestrzeni nazw http://www.w3.org/2001/XMLSchema-instance, określający lokalizację schematu. Innym językiem schematów mogącym służyć

Dziki Bill Hickok

encyclopaedia – a popular culture blending into political culture when, for instance, an American president (Dwight D. Eisenhower, in this case) during 1953

Chec 3

31 października 2023  (ang.). Israel downing Houthi missile is first instance of space warfare, „The Jerusalem Post”, 6 listopada 2023  (ang.). EmanuelE