04. Adapter

Design pattern: Adapter

DesignPattern

Intent

  • Changes interfaces of a class to support other functions.

Explain

Adapter pattern is a good way to reuse existing classes. If stack is required, there are two ways to provide it. The first way is to make stack from scratch. However, it might take a lot of effort and time. Also, after making stack, it is necessary to verify the functionality of stack. The second way is to modify existing list or deque data structure. List and deque have different policy to store and load data from stack. Therefore, it is possible to change the policy, they can be stack. Code 1 shows stack from list.

// 01_C_testStackFromList.cpp
#include <iostream>
#include <list>
using namespace std;

// Prohibits the original functions of list
template <typename T>
class Stack : private list<T>
{
public:
    inline void push(const T& a)
    {
        list<T>::push_back(a);
    }

    inline void pop()
    {
        list<T>::pop_back();
    }

    inline T& top()
    {
        return list<T>::back();
    }

    inline int size()
    {
        return list<T>::size();
    }

    // Typename let compile know list<T> is type
    inline typename list<T>::iterator begin()
    {
        return list<T>::begin();
    }

    inline typename list<T>::iterator end()
    {
        return list<T>::end();
    }
};

int main()
{
    Stack<int> stack;

    stack.push(10);
    stack.push(20);
    stack.push(30);

    int i = 0;
    //stack.push_front(10);           // push_front is forbidden
    for (auto num : stack)
    {
        cout << "Index: " << i++ << ", Value: " << num << endl;
    }

    cout << "Size at start: " << stack.size() << endl;
    int size = stack.size();
    for (int i=0; i<size; i++)
    {
        // Get a value of top
        int top = stack.top();
        cout << "Pop: " << top << ", remain: " << stack.size() << endl;
        // Remove top value
        stack.pop();
    }

    return 0;
}
// Compile: clang++ -std=c++14
//              -o 01_C_testStackFromList 01_C_testStackFromList.cpp
Code 1. Stack from list
Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Size at start: 3
Pop: 30, remain: 3
Pop: 20, remain: 2
Pop: 10, remain: 1

This stack inherits list as private, and extends push(), pop(), and top(). Also, stack overrides some functions. The reason why private is used is to hide interfaces of list. It is important to prevent a user from using a class in wrong way. If all interfaces are exposed, stack can be destroyed by push_front(). Private, and protected hide interfaces, but allows to use implementation, so it is useful for adapter pattern.

Alternatively, composition is better option than inheritance for adapter pattern. It can also hide interfaces, and allow to use implementation. Furthermore, Composition makes loosely coupling between a parent and a child class. Also, composition allows having a multiple variables from the same class. Code 2 shows how stack is implemented with composition in C++ STL.

// 02_C_StackByComposition.cpp
#include <iostream>
#include <vector>
#include <deque>

#include <algorithm>                    // For for_each
using namespace std;

template <typename T1, typename T2=deque<T1>>
class Stack
{
    T2 container;

public:
    inline void push(const T1& a)
    {
        container.push_back(a);
    }

    inline void pop()
    {
        container.pop_back();
    }

    inline T1& top()
    {
        return container.back();
    }

    inline int size()
    {
        return container.size();
    }

    inline typename T2::iterator begin()
    {
        return container.begin();
    }

    inline typename T2::iterator end()
    {
        return container.end();
    }
};

void show(int itr)
{
    cout << itr << endl;
}

int main()
{
    Stack<int> dStack;                  // Deque base stack
    dStack.push(10);
    dStack.push(20);
    dStack.push(30);

    cout << "Stack from Deque" << endl;
    for_each(dStack.begin(), dStack.end(), show);

    Stack<int, vector<int>> vStack;     // Vector base stack
    vStack.push(10);
    vStack.push(20);
    vStack.push(30);

    cout << "Stack from Vector" << endl;
    for_each(vStack.begin(), vStack.end(), show);
}
// Compile: clang++ -std=c++14
//              -o 02_C_StackByComposition 02_C_StackByComposition.cpp
Code 1. Stack by composition
Stack from Deque
10
20
30
Stack from Vector
10
20
30

Summary

  • Adapter pattern helps to make new class from existed class.
  • Adapter pattern can be implemented by Composition or private (or protected) inheritance.

COMMENTS

Name

0 weights,1,abstract class,1,active function,3,adam,2,Adapter,1,affine,2,argmax,1,back propagation,3,binary classification,3,blog,2,Bucket list,1,C++,11,Casting,1,cee,1,checkButton,1,cnn,3,col2im,1,columnspan,1,comboBox,1,concrete class,1,convolution,2,cost function,6,data preprocessing,2,data set,1,deep learning,31,Design Pattern,12,DIP,1,django,1,dnn,2,Don't Repeat Your code,1,drop out,2,ensemble,2,epoch,2,favicon,1,fcn,1,frame,1,gradient descent,5,gru,1,he,1,identify function,1,im2col,1,initialization,1,Lab,9,learning rate,2,LifeLog,1,linear regression,6,logistic function,1,logistic regression,3,logit,3,LSP,1,lstm,1,machine learning,31,matplotlib,1,menu,1,message box,1,mnist,3,mse,1,multinomial classification,3,mutli layer neural network,1,Non Virtual Interface,1,normalization,2,Note,21,numpy,4,one-hot encoding,3,OOP Principles,2,Open Close Principle,1,optimization,1,overfitting,1,padding,2,partial derivative,2,pooling,2,Prototype,1,pure virtual function,1,queue runner,1,radioButton,1,RBM,1,regularization,1,relu,2,reshape,1,restricted boltzmann machine,1,rnn,2,scrolledText,1,sigmoid,2,sigmoid function,1,single layer neural network,1,softmax,6,softmax classification,3,softmax cross entropy with logits,1,softmax function,2,softmax regression,3,softmax-with-loss,2,spinBox,1,SRP,1,standardization,1,sticky,1,stride,1,tab,1,Template Method,1,TensorFlow,31,testing data,1,this,2,tkinter,5,tooltip,1,Toplevel,1,training data,1,vanishing gradient,1,Virtual Copy Constructor,1,Virtual Destructor,1,Virtual Function,1,weight decay,1,xavier,2,xor,3,
ltr
item
Universe In Computer: 04. Adapter
04. Adapter
Design pattern: Adapter
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXvUavVsX4rYm8cgKQ8rzps7pHmmEVtkIb66G2o5KZFCfjvO96SCEUdaw_DMYzSbdVrB8XvnaKN8ljEE7EBjutI2XvsBL-2BLdijjJRIpAOEpvlhOW-hfWP3ir3wbE488AwdFEu7WKbLgO/s0/
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXvUavVsX4rYm8cgKQ8rzps7pHmmEVtkIb66G2o5KZFCfjvO96SCEUdaw_DMYzSbdVrB8XvnaKN8ljEE7EBjutI2XvsBL-2BLdijjJRIpAOEpvlhOW-hfWP3ir3wbE488AwdFEu7WKbLgO/s72-c/
Universe In Computer
https://kunicom.blogspot.com/2017/09/04-adapter.html
https://kunicom.blogspot.com/
https://kunicom.blogspot.com/
https://kunicom.blogspot.com/2017/09/04-adapter.html
true
2543631451419919204
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy