Is there a pattern similar to Singleton?

3

It's really frustrating, a bit interesting maybe, but frustrating above all, I still figured out how and why to use the Singleton standard yesterday, and today, when I was going to finish a little improvement on a project, the true face of the pattern. Let's say I'm a bit lost at the moment, for having done the system based on this pattern, being that there are about 10 classes, each containing an average of 6 ~ 7 methods, not counting the properties. I do not know the other standards because I never had the chance to try them out and see how they work, or how far they go.

Let's say I have this script :

# instancia para retornar todos os valores no banco de dados
$database = Database::getInstance()->get(false,array('nickname','like','',true));

# teste, para a mensagem da sessão
if(Session::exists('sucesso')):
    print Session::pop('sucesso');
    print "<br/>";
endif;

# teste, para a sessão
if(Session::exists(Config::get('session@session_name'))){
    //print Session::get(Config::get('session@session_name')) . "<br/>";
    print Hash::decode(Session::get(Config::get('session@session_name'))) . "<br/>";
}

# teste, para o login
# classe faz o uso de Database::getInstance()
$usuario = new User();
if($usuario->logado()){
    print "Logado";
} else {
    print "Logue primeiro";
}

# Iterar o objecto e imprimir os respectivos valores
if($database){
    print "<p><b>(".$database->count().") Resultados Encontrados</b></p>";
    $campo_s = Config::get('mysql_fetch@campo_s');
    $campo_n = Config::get('mysql_fetch@campo_n');
    foreach($database->results() as $key=>$object){
        print $object->$campo_s . ' - ' . $object->$campo_n. "<br/>";
    }
} else {
    print Database::error();
    print "Consulta não efetuada";
}

# teste, para a hora
print "<p>Data:\r<b>".Config::dateTime()."</b></p>";

Well in the first line of code of this script , I have an instance of my connection, and I also passed some parameters to make a query,

In loop% User was supposed to, I was able to print all the values corresponding to my first query in the database, but that's not what happens, I only get 1 single result, which is referent to the authenticated user. Soon I was thinking, what am I doing wrong, past 35 ~ 40s I realized that it was the standard that I am currently using, that is, if a base of operation is defined well on top, and suddenly another instruction still in the middle, the rest of the block acts according to these instructions, even if it involves rewriting the search.

At the bottom it is just a linear operation, where all the instructions are processed in line, as if it were a thin pipe.

Here is the default, used:

private function __construct(){

}
// Singleton initialization
public static function getInstance(){
    if(is_null(self::$_instance)){
        self::$_instance = new Database();
    }
    return self::$_instance;
    # Desta forma funciona, mas viola o principio do padrão aplicado
    # Procurar possível solução (encontrada).
    /*
    self::$_instance = new Database();
    return self::$_instance;
    */
}

At first I did tests to see if it was really because of the pattern, so I started at the core of that pattern, where I removed the condition responsible for creating single instances, and did the following:

self::$_instance = new Database();
return self::$_instance;

I passed the test and it worked, so I had to return the method exactly as it was, because in this way it would violate the standard, and do "I do not know what" , that somehow I had solved the problem.

Then came the head, which, because they were linear instructions and processed one by one, why not move the first instance to the end of the first block? So that's what I did.

$database = Database::getInstance()->get(false,array('nickname','like','',true));

I moved this instance to after the first, I ran the test and it worked fine.

I can say that at the moment I did not have problems using the standard in this project, but what I really want to know is:

What is the most similar pattern to Singleton , which allows me to use public methods without prior instance?

Or, what is the alternative method and can be easily implemented in a project at half, or almost at the end? Given that it would only rewrite the connection instance in the connection class, maintaining the structure in the scripts or classes that make use of it.

    
asked by anonymous 14.11.2015 / 05:00

1 answer

7

I will not answer anything from the beginning that is not very relevant because it would take a lot of time and deep down you will not want the solution I have. But it's all wrong. It is not a problem of the standard, it is the lack of it as it was conceived. This would not happen if you had developed it simply using techniques you master.

No similar pattern. In fact the most similar is not to use this pattern. Or it uses a totally static class, without having to create instance; or even the class creates, does everything "procedural". Or leave it the way it is because the problem is another. This would be the best, since it started doing so. It would be difficult to change without rethinking the whole project.

I think you've fallen into design pattern syndrome . Which is very common. He'd heard so much about DP that he thought he had to use it somewhere. Can you say any real advantage to your code obtained by using it? Be compared with a static class, or no class at all.

I feel like you just wanted to take a trip and had to learn mechanics and ride the engine to get what you wanted. Obviously the first mounts will go wrong. When you start riding right, you'll realize you did not have to do this.

Experienced programmers - and not stubborn - have learned (or have been wrong, or have read good publications, or by self-perception) that it is easier just to make the trip.

    
14.11.2015 / 12:29