Skip to content

Commit 89d1b9e

Browse files
committed
State pattern added
1 parent 6383491 commit 89d1b9e

13 files changed

+610
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ I'm adding new samples from time to time.
88
2. Chain Of Responsibility (COF) Pattern Java Examples 2
99
3. Chain Of Responsibility (COF) Pattern Java Examples 3
1010
4. Interpreter Pattern Java Examples
11+
5. Singleton (EagerInitialization,as Enum,LazyInitialization,StaticBlockInitialization,ThreadSafe)
12+
6. State
1113

1214
# Contribute
1315

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
The MIT License (MIT)
3+
4+
Copyright (c) 2015 Massimo Caliman
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.
23+
*/
24+
package io.github.mcaliman.patterns.singletion;
25+
26+
/**
27+
* Se l'applicazione ha sempre necessità di una istanza, o se il costo di
28+
* creazione della stessa non è troppo grande in termini di tempo e risorse, si
29+
* può utilizzare questa modalità che crea sempre un istanza.
30+
* <p>
31+
* L'Eager (impaziente!) Initialization Singleton è un singleton impaziente di inizializzare
32+
* la sua unica istanza possibile.
33+
*
34+
* @author Massimo Caliman
35+
*/
36+
public class EagerInitializationSingleton {
37+
38+
/**
39+
* Istanza creata all'atto di caricamento della classe in memoria
40+
* quindi è thread-safe! Le convenzioni sono importanti
41+
* INSTANCE è scritto in maiscolo in quanto final e static.
42+
*/
43+
private final static EagerInitializationSingleton INSTANCE = new EagerInitializationSingleton();
44+
/**
45+
* Il singleton è utile se contiene o fa qualcosa, ecco quindi
46+
* un unica proprietà (dummy) accessive solo tramite setter e getter
47+
* appositi.
48+
*/
49+
private String property = "EagerInitializationSingleton property value.";
50+
51+
/**
52+
* Il costruttore è privato, in quanto la creazione dell'istanza deve essere
53+
* controllata. Può avvenire solo all'interno della classe Singleton.
54+
*/
55+
private EagerInitializationSingleton() {
56+
System.out.println("Istanza di EagerInitializationSingleton creata! Questo messaggio non dovrà apparire più di una volta.");
57+
}
58+
59+
/**
60+
* Unico punto di accesso al Singleton tramite metodo pubblico e statico.
61+
*
62+
* @return il Singleton
63+
*/
64+
public static EagerInitializationSingleton getInstance() {
65+
return INSTANCE;
66+
}
67+
68+
public String getProperty() {
69+
return property;
70+
}
71+
72+
public void setProperty(String property) {
73+
this.property = property;
74+
}
75+
76+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
The MIT License (MIT)
3+
4+
Copyright (c) 2015 Massimo Caliman
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.
23+
*/
24+
package io.github.mcaliman.patterns.singletion;
25+
26+
/**
27+
* Un modo originale (ed elegante) di realizzare un singleton con enum
28+
* Se sei interessato ad approfondire dai una lettura alla seconda edizione
29+
* di "Effective Java" di Joshua Bloch.
30+
* <p>
31+
* Questo approccio è funzionalmente equivalente al metodo con campo public (vedi gli altri
32+
* esempi),è più conciso e fornisce:
33+
* 1. Il meccanismo di serializzazione (gratuitamente)
34+
* 2. Una garanzia di protezione contro le istanze multiple
35+
* Ad oggi è comunque ancora relativamente sconosciuto e raramente utilizzato.
36+
*
37+
* @author Massimo Caliman
38+
*/
39+
public enum EnumSingleton {
40+
41+
INSTANCE;
42+
43+
public String getProperty() {
44+
return "EnumSingleton property value.";
45+
}
46+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
The MIT License (MIT)
3+
4+
Copyright (c) 2015 Massimo Caliman
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.
23+
*/
24+
package io.github.mcaliman.patterns.singletion;
25+
26+
/**
27+
* Un singleton "pigro" (lazy). Inizializza (con tutti i relativi vantaggi)
28+
* la sua istanza solo quando necessario.
29+
*
30+
* @author Massimo Caliman
31+
*/
32+
public class LazyInitializationSingleton {
33+
34+
private static LazyInitializationSingleton instance = null;
35+
/**
36+
* La proprietà (anche se è un dummy!) che giustifica il singleton (qualcosa
37+
* dovrà pur fare o comunicare.
38+
*/
39+
private String property = "LazyInitializationSingleton property value.";
40+
41+
/**
42+
* Il costruttore privato impedisce l'istanza di oggetti da parte di classi esterne.
43+
*/
44+
private LazyInitializationSingleton() {
45+
System.out.println("Istanza di LazyInitializationSingleton creata! Questo messaggio non dovrà apparire più di una volta.");
46+
}
47+
48+
/**
49+
* Metodo della classe impiegato per accedere al singleton. E'per ovvi motivi
50+
* sincronizzato (con due thread tentano di accedere si rischia la doppia istanza).
51+
*
52+
* @return il singleton.
53+
*/
54+
public static synchronized LazyInitializationSingleton getInstance() {
55+
if (instance == null) {
56+
instance = new LazyInitializationSingleton();
57+
}
58+
return instance;
59+
}
60+
61+
public String getProperty() {
62+
return property;
63+
}
64+
65+
public void setProperty(String property) {
66+
this.property = property;
67+
}
68+
69+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
The MIT License (MIT)
3+
4+
Copyright (c) 2015 Massimo Caliman
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.
23+
*/
24+
package io.github.mcaliman.patterns.singletion;
25+
26+
/**
27+
* Chiamiamo i nostri vari singleton
28+
*
29+
* @author Massimo Caliman
30+
*/
31+
public class SingletonPatternJavaExamples {
32+
33+
public static void main(String[] args) {
34+
System.out.println("EagerInitializationSingleton.getInstance().getProperty()=" + EagerInitializationSingleton.getInstance().getProperty());
35+
System.out.println("EnumSingleton.INSTANCE.getProperty()=" + EnumSingleton.INSTANCE.getProperty());
36+
System.out.println("LazyInitializationSingleton.getInstance().getProperty()=" + LazyInitializationSingleton.getInstance().getProperty());
37+
System.out.println("StaticBlockInitializationSingleton.getInstance().getProperty()=" + StaticBlockInitializationSingleton.getInstance().getProperty());
38+
System.out.println("ThreadSafeSingleton.getInstance().getProperty()=" + ThreadSafeSingleton.getInstance().getProperty());
39+
}
40+
41+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
The MIT License (MIT)
3+
4+
Copyright (c) 2015 Massimo Caliman
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.
23+
*/
24+
package io.github.mcaliman.patterns.singletion;
25+
26+
/**
27+
* Singleton che realizza una forma di pre-elaborazione ( utile ad esempio per
28+
* il controllo degli errori).
29+
*
30+
* @author mcaliman
31+
*/
32+
public class StaticBlockInitializationSingleton {
33+
34+
private final static StaticBlockInitializationSingleton INSTANCE;
35+
36+
static {
37+
try {
38+
INSTANCE = new StaticBlockInitializationSingleton();
39+
} catch (Exception e) {
40+
throw new RuntimeException("error occurred.", e);
41+
}
42+
}
43+
44+
private String property = "StaticBlockInitializationSingleton property value.";
45+
46+
private StaticBlockInitializationSingleton() {
47+
//dovrebbe contiene qualcosa che potrebbe lanciare un eccezione...
48+
System.out.println("Istanza di StaticBlockInitializationSingleton creata! Questo messaggio non dovrà apparire più di una volta.");
49+
}
50+
51+
public static StaticBlockInitializationSingleton getInstance() {
52+
return INSTANCE;
53+
}
54+
55+
public String getProperty() {
56+
return property;
57+
}
58+
59+
public void setProperty(String property) {
60+
this.property = property;
61+
}
62+
63+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
The MIT License (MIT)
3+
4+
Copyright (c) 2015 Massimo Caliman
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.
23+
*/
24+
package io.github.mcaliman.patterns.singletion;
25+
26+
/**
27+
* Un altro tipo di singleton sicuro rispetto al multi-thread.
28+
*
29+
* @author Massimo Caliman
30+
*/
31+
public class ThreadSafeSingleton {
32+
33+
/**
34+
* volatile garantisce che i cambiamenti siano visti immediatamente da tutti
35+
* gli altri thread
36+
*/
37+
private static volatile ThreadSafeSingleton instance = null;
38+
private String property = "ThreadSafeSingleton property value.";
39+
40+
/**
41+
* Il costruttore private impedisce l'istanza di oggetti da parte di classi
42+
* esterne
43+
*/
44+
private ThreadSafeSingleton() {
45+
System.out.println("Istanza di ThreadSafeSingleton creata! Questo messaggio non dovrà apparire più di una volta.");
46+
}
47+
48+
/**
49+
* Per accedere al singleton (vedi le altre classi di esempio e relativi
50+
* commenti).
51+
*
52+
* @return il singleton
53+
*/
54+
public static ThreadSafeSingleton getInstance() {
55+
if (instance == null) {
56+
/*
57+
* E' possibile rendere synchronized solo questa parte del metodo perché l'istanza
58+
* è di tipo volatile. Meno parte di un blocco di codice si riesce a rendere
59+
* synchronized meglio è...
60+
*/
61+
synchronized (ThreadSafeSingleton.class) {
62+
//non sono sicuro di essere ancora il primo thread ad accedere al metodo,
63+
//quindi ricontrollo
64+
if (instance == null) {
65+
instance = new ThreadSafeSingleton();
66+
}
67+
}
68+
}
69+
return instance;
70+
}
71+
72+
public String getProperty() {
73+
return property;
74+
}
75+
76+
public void setProperty(String property) {
77+
this.property = property;
78+
}
79+
80+
}

0 commit comments

Comments
 (0)