Really complicated way
to perform a simple task
@Cadovvl 2015
На собеседовании спросите, знает ли человек, чем отличается Decorator от Facade.
На собеседовании спросите, знает ли человек, чем отличается Decorator от Facade.
Если знает: найдите любой предлог, чтобы не брать его...
Singletone
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object
class Singletone {
private Singletone() {
}
// there is only one instance created
static public Singletone getInstance() {
// do some staff
return null;
}
}Double-Checked Locking Problem
class Singletone {
private static Singletone instance = null;
// there is only one instance created
static public Singletone getInstance() {
if (instance == null) {
instance = new Singletone();
}
return instance;
}
private Singletone() {
}
}Singletone, student lab lvl
static public Singletone getInstance() {
if (instance == null) {
instance = new Singletone();
}
return instance;
}
Singletone, student lab lvl
Thread 1
Thread 2
static public Singletone getInstance() {
if (instance == null) {
instance = new Singletone();
}
return instance;
}
1
3
5
2
4
6
class Singletone {
private static Singletone instance = null;
// there is only one instance created
static synchronized public Singletone getInstance() {
if (instance == null) {
instance = new Singletone();
}
return instance;
}
private Singletone() {
}
}Syncronized Singletone
class Singletone {
private static Singletone instance = null;
// there is only one instance created
static public Singletone getInstance() {
if (instance == null) {
synchronized(Singletone.class) {
instance = new Singletone();
}
}
return instance;
}
private Singletone() {
}
}Syncronized Singletone
a bit optimally
static public Singletone getInstance() {
if (instance == null) {
synchronized(Singletone.class) {
instance = new Singletone();
}
}
return instance;
}
Syncronized Singletone
a bit optimally
Thread 1
Thread 2
1
3
4
2
5
6
static public Singletone getInstance() {
if (instance == null) {
synchronized(Singletone.class) {
instance = new Singletone();
}
}
return instance;
}
class Singletone {
private static Singletone instance = null;
// there is only one instance created
static public Singletone getInstance() {
if (instance == null) {
synchronized(Singletone.class) {
if (instance == null) {
instance = new Singletone();
}
}
}
return instance;
}
private Singletone() {
}
}Syncronized Singletone
with double check
class Singletone {
private static Singletone instance = null;
// there is only one instance created
static public Singletone getInstance() {
if (instance == null) {
synchronized(Singletone.class) {
if (instance == null) {
instance = new Singletone();
}
}
}
return instance;
}
private Singletone() {
}
}Syncronized Singletone
with double check
class Singletone {
private static Singletone instance = null;
// there is only one instance created
static public Singletone getInstance() {
if (instance == null) {
synchronized(Singletone.class) {
if (instance == null) {
// there are two operations in a code below
instance = new Singletone();
/* *****
* move reference to instance location
* *****
* call Singleton's ctor
* *****
**/
}
}
}
return instance;
}
private Singletone() {
}
}
Syncronized Singletone
with double check
static public Singletone getInstance() {
if (instance == null) {
synchronized(Singletone.class) {
if (instance == null) {
instance = new Singletone();
/* *****
* move reference to instance location
* *****
* call Singleton's ctor
* *****
**/
}
}
}
return instance;
}Syncronized Singletone
with double check
static public Singletone getInstance() {
if (instance == null) {
synchronized(Singletone.class) {
if (instance == null) {
instance = new Singletone();
/* *****
* move reference to instance location
* *****
* call Singleton's ctor
* *****
**/
}
}
}
return instance;
}Thread 1
Thread 2
1
2
5
3
4
class Singletone {
private static Singletone instance = null;
// there is only one instance created
static public Singletone getInstance() {
if (instance == null) {
synchronized(Singletone.class) {
if (instance == null) {
Singletone temp;
synchronized(Singletone.class) {
temp = new Singletone();
}
instance = temp;
}
}
}
return instance;
}
private Singletone() {
}
}Syncronized Singletone
with double check and double sync
class Singletone {
private static Singletone instance = null;
// there is only one instance created
static public Singletone getInstance() {
if (instance == null) {
synchronized(Singletone.class) {
if (instance == null) {
Singletone temp;
synchronized(Singletone.class) {
temp = new Singletone();
instance = temp;
}
// instance = temp;
}
}
}
return instance;
}
private Singletone() {
}
}
Syncronized Singletone
with double check and double sync
Допустимая
оптимизация
Ожидаемый
Singleton
Ожидаемый
Singleton
class Singletone {
private static Singletone instance = new Singletone();
// there is only one instance created
static public Singletone getInstance() {
return instance;
}
}Factory
AbstractFactory
MetaAbstractFactory
GeneralizedMetaAbstractFactory
Любая(!) фабрика противоречит
Open Closed Principle
Factory
interface Dog
{
public void speak ();
}class Poodle implements Dog
{
public void speak()
{
System.out.println("The poodle says \"arf\"");
}
}
class Rottweiler implements Dog
{
public void speak()
{
System.out.println("The Rottweiler says (in a very deep voice) \"WOOF!\"");
}
}
class SiberianHusky implements Dog
{
public void speak()
{
System.out.println("The husky says \"Dude, what's up?\"");
}
}class DogFactory
{
public static Dog getDog(String criteria)
{
if ( criteria.equals("small") )
return new Poodle();
else if ( criteria.equals("big") )
return new Rottweiler();
else if ( criteria.equals("working") )
return new SiberianHusky();
return null;
}
}Factory
interface Dog
{
public void speak ();
}class Poodle implements Dog
{
public void speak()
{
System.out.println("The poodle says \"arf\"");
}
}
class Rottweiler implements Dog
{
public void speak()
{
System.out.println("The Rottweiler says (in a very deep voice) \"WOOF!\"");
}
}
class SiberianHusky implements Dog
{
public void speak()
{
System.out.println("The husky says \"Dude, what's up?\"");
}
}class DogFactory
{
public static Dog getDog(String criteria)
{
if ( criteria.equals("small") )
return new Poodle();
else if ( criteria.equals("big") )
return new Rottweiler();
else if ( criteria.equals("working") )
return new SiberianHusky();
return null;
}
}Как добавить таксу, не изменяя реализации DogFactory?
Factory
Комментарии к записи в блоге
thx
Submitted by koko (not verified) on January 19, 2010 - 4:51pm
this pattern example help me a lots. Thankyou verymuch.Very Helpful
Submitted by Josh (not verified) on March 6, 2010 - 2:17pm
Thanks a ton for this example. Really well thought out, and I felt it cut right
to the heart of factory patterns and provided a nice simple example. Thanks again!
Good
Submitted by Mubarak (not verified) on March 18, 2010 - 6:48am
Its very useful for me.i dont know concept of factory pattern but
once i read this and very clear this factory concept.
Thank you so much..Simple and Precise
Submitted by Deepthi (not verified) on March 25, 2010 - 6:41am
Thank you for the neat example. doesnt confuse like many other examples
available on net.
Factory
Примеры правильных мест для использования
- Геометрические фигуры
- Генератор диалоговых окон в интерфейсе
- Стандартизированные вызовы (GET, POST, PUT....)
- Обработчики тестовых данных (fb2, txt, epub, ...)
- Прочие примеры, с небольшим списком объектов и маловероятным его обновлением.
AbstractFactory
Как вариант удовлетворения Open Close Priciple
Не будет кода, слишком его многоAbstractFactory
Как вариант удовлетворения Open Close Priciple
Не будет кода, слишком его многоAbstract Factory не удовлетворяет Open Closed Principle
Для добавления в AbstractFactory нового "класса" (от kind) продуктов нужно менять ее интерфейс и, следовательно, все реализации.
MetaAbstractFactory
Как вариант удовлетворения Open Close Priciple

Inheritance
Inheritance
public abstract class Base {
abstract String getSupportedTaskType();
// Some staff
}
public class Derived extends Base {
@Override
String getSupportedTaskType() {
return "task_type_1";
}
}Ради чего все это было?
Ради чего все это было?
Научите меня, как бить по рукам так, чтобы больше не хотелось использовать такого говна в коде...
Thx

Сложные решения простых задач
By Cadovvl
Сложные решения простых задач
Немного о паттернах проектирования и рациональности их использования
- 400