lundi 21 janvier 2019

Is implementation of adapter pattern correct?

I'm learning how to implement adapter pattern. After reading few articles I decided to write some code. I want to display post from social media. I have two classes of social media which have methods to display post. The methods' names are diffeerent. I created SmAdapter class where instance of social media is injected. Then, depending on type of social media class approprate displaying method is used. Whole process is closed in SmAdapter display method. On the client side it's only necessarily to instantiate two obejcts of Smadapter and Social Media cklasses.

 class Facebook implements SmAuth

{
    public function authenticate()
    {
        return 'authenticate';
    }

    public function fdisplay()
    {

        return 'facebook post';
    }

}

class Twitter implements SmAuth
{
    public function authenticate()
    {
        return 'authenticate';
    }

    public function tdisplay()
    {

        return 'Twitter post';
    }


}

interface SmAuth
{

    public function authenticate();

}

interface Sm
{

    public function display();

}

class Smadapter implements Sm
{

    public function __construct(SmAuth $sm)
    {
        $this->sm = $sm;
    }
    public function display()
    {
        if ($this->sm instanceof Facebook) {
            return $this->sm->fdisplay();
        }
        if ($this->sm instanceof Twitter) {
            return $this->sm->tdisplay();
        }

    }

}

public function test()
    {

        $f = new Facebook();
        $sm = new Smadapter($f);
        return $sm->display();
    }

Is my code correct?

Aucun commentaire:

Enregistrer un commentaire