खोज…


सी ++ में विज़िटर पैटर्न उदाहरण

के बजाय

struct IShape
{
    virtual ~IShape() = default;

    virtual void print() const = 0;
    virtual double area() const = 0;
    virtual double perimeter() const = 0;
    // .. and so on
};

आगंतुकों का उपयोग किया जा सकता है:

// The concrete shapes
struct Square;
struct Circle;

// The visitor interface
struct IShapeVisitor
{
    virtual ~IShapeVisitor() = default;
    virtual void visit(const Square&) = 0;
    virtual void visit(const Circle&) = 0;
};

// The shape interface
struct IShape
{
    virtual ~IShape() = default;

    virtual void accept(IShapeVisitor&) const = 0;
};

अब ठोस आकार:

struct Point {
    double x;
    double y;
};

struct Circle : IShape
{
    Circle(const Point& center, double radius) : center(center), radius(radius) {}
    
    // Each shape has to implement this method the same way
    void accept(IShapeVisitor& visitor) const override { visitor.visit(*this); }

    Point center;
    double radius;
};

struct Square : IShape
{
    Square(const Point& topLeft, double sideLength) :
         topLeft(topLeft), sideLength(sideLength)
    {}

    // Each shape has to implement this method the same way
    void accept(IShapeVisitor& visitor) const override { visitor.visit(*this); }

    Point topLeft;
    double sideLength;
};

तब आगंतुक:

struct ShapePrinter : IShapeVisitor
{
    void visit(const Square&) override { std::cout << "Square"; }
    void visit(const Circle&) override { std::cout << "Circle"; }
};

struct ShapeAreaComputer : IShapeVisitor
{
    void visit(const Square& square) override
    {
        area = square.sideLength * square.sideLength;
    }

    void visit(const Circle& circle) override
    {
         area = M_PI * circle.radius * circle.radius;
    }

    double area = 0;
};

struct ShapePerimeterComputer : IShapeVisitor
{
    void visit(const Square& square) override { perimeter = 4. * square.sideLength; }
    void visit(const Circle& circle) override { perimeter = 2. * M_PI * circle.radius; }

    double perimeter = 0.;
};

और इसका उपयोग करें:

const Square square = {{-1., -1.}, 2.};
const Circle circle{{0., 0.}, 1.};
const IShape* shapes[2] = {&square, &circle};

ShapePrinter shapePrinter;
ShapeAreaComputer shapeAreaComputer;
ShapePerimeterComputer shapePerimeterComputer;

for (const auto* shape : shapes) {
    shape->accept(shapePrinter);
    std::cout << " has an area of ";

    // result will be stored in shapeAreaComputer.area
    shape->accept(shapeAreaComputer);

    // result will be stored in shapePerimeterComputer.perimeter
    shape->accept(shapePerimeterComputer); 

    std::cout << shapeAreaComputer.area
              << ", and a perimeter of "
              << shapePerimeterComputer.perimeter
              << std::endl;
}

अपेक्षित उत्पादन:

Square has an area of 4, and a perimeter of 8
Circle has an area of 3.14159, and a perimeter of 6.28319

डेमो

स्पष्टीकरण :

  • void Square::accept(IShapeVisitor& visitor) const override { visitor.visit(*this); } , के स्थिर प्रकार this जाना जाता है, और इसलिए (संकलन समय पर) चुना अधिभार है void IVisitor::visit(const Square&);

  • square.accept(visitor); लिए। square.accept(visitor); कॉल, virtual माध्यम से डायनामिक डिस्पैच का उपयोग यह जानने के लिए किया जाता है कि कौन कॉल accept है।

पेशेवरों :

  • आप एक नए आगंतुक को जोड़कर केवल कक्षा IShape नई कार्यक्षमता ( SerializeAsXml , ...) जोड़ सकते हैं।

विपक्ष :

  • एक नया ठोस आकार जोड़ना ( Triangle , ...) सभी आगंतुकों को संशोधित करने की आवश्यकता है।

IShape में virtual फ़ंक्शंस के रूप में सभी IShape डालने के विकल्प के विपरीत पेशेवरों और विपक्ष हैं: नई कार्यक्षमता को जोड़ने के लिए सभी मौजूदा आकृतियों को संशोधित करना आवश्यक है, लेकिन एक नया आकार जोड़ना मौजूदा कक्षाओं को प्रभावित नहीं करता है।

जावा में आगंतुक पैटर्न उदाहरण

Visitor पैटर्न आपको उन कक्षाओं की संरचना को संशोधित किए बिना वर्गों के एक सेट में नए संचालन या विधियों को जोड़ने की अनुमति देता है।

यह पैटर्न विशेष रूप से तब उपयोगी होता है जब आप किसी वस्तु पर किसी वस्तु के विस्तार के बिना या वस्तु को संशोधित किए बिना किसी विशेष ऑपरेशन को केंद्रीकृत करना चाहते हैं।

विकिपीडिया से यूएमएल आरेख:

यहाँ छवि विवरण दर्ज करें

सांकेतिक टुकड़ा:

import java.util.HashMap;

interface Visitable{
    void accept(Visitor visitor);
}

interface Visitor{
    void logGameStatistics(Chess chess);
    void logGameStatistics(Checkers checkers);
    void logGameStatistics(Ludo ludo);    
}
class GameVisitor implements Visitor{
    public void logGameStatistics(Chess chess){
        System.out.println("Logging Chess statistics: Game Completion duration, number of moves etc..");    
    }
    public void logGameStatistics(Checkers checkers){
        System.out.println("Logging Checkers statistics: Game Completion duration, remaining coins of loser");    
    }
    public void logGameStatistics(Ludo ludo){
        System.out.println("Logging Ludo statistics: Game Completion duration, remaining coins of loser");    
    }
}

abstract class Game{
    // Add game related attributes and methods here
    public Game(){
    
    }
    public void getNextMove(){};
    public void makeNextMove(){}
    public abstract String getName();
}
class Chess extends Game implements Visitable{
    public String getName(){
        return Chess.class.getName();
    }
    public void accept(Visitor visitor){
        visitor.logGameStatistics(this);
    }
}
class Checkers extends Game implements Visitable{
    public String getName(){
        return Checkers.class.getName();
    }
    public void accept(Visitor visitor){
        visitor.logGameStatistics(this);
    }
}
class Ludo extends Game implements Visitable{
    public String getName(){
        return Ludo.class.getName();
    }
    public void accept(Visitor visitor){
        visitor.logGameStatistics(this);
    }
}

public class VisitorPattern{
    public static void main(String args[]){
        Visitor visitor = new GameVisitor();
        Visitable games[] = { new Chess(),new Checkers(), new Ludo()};
        for (Visitable v : games){
            v.accept(visitor);
        }
    }
}

स्पष्टीकरण:

  1. Visitable ( Element ) एक इंटरफ़ेस है और इस इंटरफ़ेस विधि को कई वर्गों में जोड़ा जाना है।
  2. Visitor एक इंटरफ़ेस है, जिसमें Visitable तत्वों पर एक ऑपरेशन करने के तरीके शामिल हैं।
  3. GameVisitor एक वर्ग है, जो लागू करता है Visitor इंटरफेस ( ConcreteVisitor )।
  4. प्रत्येक Visitable तत्व Visitor स्वीकार करता है और Visitor इंटरफ़ेस की एक प्रासंगिक विधि लागू करता है।
  5. आप Game को Element रूप में और कंक्रीट गेम को Chess,Checkers and Ludo को ConcreteElements रूप में ConcreteElements

उपरोक्त उदाहरण में, Chess, Checkers and Ludo तीन अलग-अलग खेल (और Visitable कक्षाएं) हैं। एक ठीक दिन पर, मुझे प्रत्येक गेम के आँकड़े लॉग करने के लिए एक परिदृश्य का सामना करना पड़ा। इसलिए आँकड़ों की कार्यक्षमता को लागू करने के लिए व्यक्तिगत वर्ग को संशोधित किए बिना, आप GameVisitor वर्ग में उस जिम्मेदारी को केंद्रीकृत कर सकते हैं, जो प्रत्येक गेम की संरचना को संशोधित किए बिना आपके लिए चाल चलता है।

उत्पादन:

Logging Chess statistics: Game Completion duration, number of moves etc..
Logging Checkers statistics: Game Completion duration, remaining coins of loser
Logging Ludo statistics: Game Completion duration, remaining coins of loser

उपयोग मामलों / प्रयोज्यता:

  1. एक संरचना में समूहीकृत विभिन्न प्रकारों की वस्तुओं पर समान संचालन करना होता है
  2. आपको कई विशिष्ट और असंबंधित कार्यों को निष्पादित करने की आवश्यकता है। यह ऑपरेशन को ऑब्जेक्ट्स स्ट्रक्चर से अलग करता है
  3. ऑब्जेक्ट संरचना में बदलाव के बिना नए संचालन को जोड़ना होगा
  4. किसी एकल वर्ग में संबंधित परिचालनों को इकट्ठा करने के बजाय आपको कक्षाएं बदलने या निकालने के लिए बाध्य करें
  5. वर्ग पुस्तकालयों के लिए फ़ंक्शंस जोड़ें जिनके लिए आपके पास स्रोत नहीं है या स्रोत को बदल नहीं सकते हैं

अतिरिक्त संदर्भ:

oodesign

sourcemaking

C ++ में आगंतुक उदाहरण

// A simple class hierarchy that uses the visitor to add functionality.
//
class VehicleVisitor;
class Vehicle
{
    public:
        // To implement the visitor pattern
        // The class simply needs to implement the accept method 
        // That takes a reference to a visitor object that provides
        // new functionality.
        virtual void accept(VehicleVisitor& visitor) = 0
};
class Plane: public Vehicle
{
    public:
        // Each concrete representation simply calls the visit()
        // method on the visitor object passing itself as the parameter.
        virtual void accept(VehicleVisitor& visitor) {visitor.visit(*this);}

        void fly(std::string const& destination);
};
class Train: public Vehicle
{
    public:
        virtual void accept(VehicleVisitor& visitor) {visitor.visit(*this);}

        void locomote(std::string const& destination);
};
class Automobile: public Vehicle
{
    public:
        virtual void accept(VehicleVisitor& visitor) {visitor.visit(*this);}

        void drive(std::string const& destination);
};

class VehicleVisitor
{
    public:
        // The visitor interface implements one method for each class in the
        // hierarchy. When implementing new functionality you just create the
        // functionality required for each type in the appropriate method.

        virtual void visit(Plane& object)      = 0;
        virtual void visit(Train& object)      = 0;
        virtual void visit(Automobile& object) = 0;

    // Note: because each class in the hierarchy needs a virtual method
    // in visitor base class this makes extending the hierarchy ones defined
    // hard.
};

एक उदाहरण का उपयोग:

// Add the functionality `Move` to an object via a visitor.
class MoveVehicleVisitor
{
    std::string const& destination;
    public:
        MoveVehicleVisitor(std::string const& destination)
            : destination(destination)
    {}
    virtual void visit(Plane& object)      {object.fly(destination);}
    virtual void visit(Train& object)      {object.locomote(destination);}
    virtual void visit(Automobile& object) {object.drive(destination);}
};

int main()
{
    MoveVehicleVisitor  moveToDenver("Denver");
    Vehicle&            object = getObjectToMove();
    object.accept(moveToDenver);
}

बड़ी वस्तुओं का पता लगाना

विज़िटर पैटर्न का उपयोग संरचनाओं को पार करने के लिए किया जा सकता है।

class GraphVisitor;
class Graph
{
    public:
        class Node
        {
            using Link = std::set<Node>::iterator;
            std::set<Link>   linkTo;
            public:
                void accept(GraphVisitor& visitor);
        };

        void accept(GraphVisitor& visitor);

    private:
        std::set<Node>  nodes;
};

class GraphVisitor
{
    std::set<Graph::Node*>  visited;
    public:
        void visit(Graph& graph)
        {
            visited.clear();
            doVisit(graph);
        } 
        bool visit(Graph::Node& node)
        {
            if (visited.find(&node) != visited.end()) {
                return false;
            }
            visited.insert(&node);
            doVisit(node);
            return true;
        }
    private: 
        virtual void doVisit(Graph& graph)      = 0;
        virtual void doVisit(Graph::Node& node) = 0;
};

void accept(GraphVisitor& visitor)
{
    // Pass the graph to the visitor.
    visitor.visit(*this);

    // Then do a depth first search of the graph.
    // In this situation it is the visitors responsibility
    // to keep track of visited nodes.
    for(auto& node: nodes) {
        node.accept(visitor);
    }
}
void Graph::Node::accept(GraphVisitor& visitor)
{
    // Tell the visitor it is working on a node and see if it was 
    // previously visited.
    if (visitor.visit(*this)) {

        // The pass the visitor to all the linked nodes.
        for(auto& link: linkTo) {
            link->accept(visitor);
        }
    }
}


Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow