Expression Tree Code Segments - PowerPoint PPT Presentation

About This Presentation
Title:

Expression Tree Code Segments

Description:

Ternary.h // A. Subramanian and T. Lambert. virtual void print (ostream &) const; ... Therefore when print is called on a node that is a ternary node, ... – PowerPoint PPT presentation

Number of Views:63
Avg rating:3.0/5.0
Slides: 58
Provided by: DrBetty3
Learn more at: http://www.cse.msu.edu
Category:

less

Transcript and Presenter's Notes

Title: Expression Tree Code Segments


1
Expression TreeCode Segments
2
Tree Case Study
  • Tree.h/Tree.C (p. 15/37-38)
  • Node.h (p. 14)
  • Int_Node.h/Int_Node.C (p. 16/20)
  • Unary_Node.h/Unary_Node.C (p. 17/21)
  • Binary_Node.h/Binary_Node.C (p. 18/22)
  • Factory Pattern Implementation for initializing
    Node subclasses (p. 26)
  • Bridge Pattern for printing subtrees (p. 31,
    short)
  • Adapter Pattern integrates Tree print with C
    I/O Streams (p. 36)
  • Main Program (p. 39)
  • Ternary_Node.h/Ternary_Node.C (p. 42/43-44)

Ramy, Xing
Biyani, Mehta
Vincent, Bao
Huang, King, Liu
3
Arun, Tony
3
Node.h
  • // R. Shahin and X. Fang
  • class Tree // Forward declaration because the
    Tree class is used by Node
  • //Describes the Tree vertices
  • class Node //Abstract class Node, base
    for concrete Node types
  • friend class Tree //BAD DESIGN.. Tree breaks
    the encapsulation of Node
  • protected //Only visible to derived classes,
    and to Tree of course
  • // A protected default constructor that
    initializes the reference count to 1
  • // This constructor is protected to prevent any
    other objects to create
  • // any instances of the Node class hierarchy
    except through the factory
  • // interface (the Tree class). That's the reason
    why Tree is declared as
  • // a friend class so that it has access to the
    protected constructors.
  • Node(void) use_ (1)

4
Node.h (cont.)
  • // An interface (pure virtual) function to print
    the node to an output stream
  • / pure / virtual void print (ostream ) const
    0
  • // Important to make destructor virtual because
    the specific destructors
  • // will be determined at run-time using dynamic
    binding
  • virtual Node (void)
  • private int use_
  • //Counter of the number of references to the
    current Node object
  • endif

5
Tree.h
  • // Bridge class that describes the Tree edges and
    acts as a factory
  • // Tree acts both as a bridge to the Node class
    hierarchy and also as
  • // a Node factory since Node object creation
    can't take place except
  • // through the Factory operations (constructors)
    of the Tree class
  • // Typically, the Node class hierarchy should be
    hidden from any client
  • // classes. An even better implementation would
    encapsulate the Node class
  • // hierarchy as inner classes in the Tree class.
    This will also eliminate
  • // the need of declaring Tree as a friend of the
    Node class.
  • // A Tree structure is defined as a recursive
    structure of Tree objects
  • class Tree
  • public // Factory operations

6
Tree.h (Cont)
  • // Constructor creating a tree with an integer
    node
  • Tree (int)
  • // Constructor creating a tree with a unary node
  • Tree (const char , Tree )
  • // Constructor creating a gree with a binary
    node
  • Tree (const char , Tree , Tree )
  • // Copy constructor
  • Tree (const Tree )
  • // Tree assignment operator void operator
    (const Tree )
  • // Tree destructor
  • Tree(void)
  • // To print a Tree object to an output stream
  • void print (ostream ) const
  • private
  • // A pointer to the rooted subtree represented
    by this tree object
  • Node node_
  • endif

7
Tree.cc
  • // Copy constructor
  • // copying the object state
  • TreeTree (const Tree t) node_ (t.node_)
  • // increment the number of references to the
  • // copied object by 1
  • ((this-gtnode_)-gtuse_)
  • //------------------------------------------------
    -----

8
Tree.cc (Cont)
  • // Tree assignment operator
  • // A BIG PROBLEM with this method is that it
    returns
  • // nothing, which means that cascading
    assignments won't
  • // work. For example if a, b and c are Tree
    objects, an
  • // expression like (a b c) won't work. It
    would be
  • // better to return a Tree, which will be
    (this) at
  • // the end of the method
  • void Treeoperator (const Tree t)
  • // increment the number of references to the
  • // copied object by 1
  • ((t.node_)-gtuse_)

9
Tree.cc (Cont)
  • // decrement the number of references to the
  • // current object by 1 since it's being
    overwritten
  • // An explicit call to the destructor would have
  • // eliminated code redundancy
  • --((this-gtnode)-gtuse_)
  • // if no one refers to the current object anymore
  • if (((this-gtnode_)-gtuse_) 0)
  • // deallocate the memory of the node object
  • delete this-gtnode_
  • // copy the node of the copied object into the
    node
  • // of the current object (copying the object
    state)
  • this-gtnode_ t.node_

10
Tree.cc (Cont)
  • // Tree destructor
  • TreeTree(void)
  • // decrement the no. of references to the
  • // current object by 1
  • --((this-gtnode_)-gtuse_)
  • // if no one refers to the current object
    anymore
  • if (this-gtnode_-gtuse_ lt 0)
  • // deallocate the memory of the node object
  • delete this-gtnode_

11
Mehta and Biyani
12
  • //
  • //Binary_Node.h Interface File for Binary Node
    Class
  • //Created by D. Schmidt and D. Levine
  • //Modified by Pradeep Vincent, 25th Feb 2001,
    Michigan State University
  • //as part of CSE 870(Advanced Software
    Engineering Course, SS01)
  • //Point of Contact Dr. Betty Cheng(chengb_at_cse.msu
    .edu)
  • //
  • include Node.h //Include Node interface file
  • //Binary Node Interface Definition
  • class Binary_Node public Node
  • public
  • Binary_Node (const char op, //Constructor for
    Binary_Node
  • const Tree t1, // Takes a operator and two
    operands
  • const Tree t2) // The two operands are two
    sub-trees of the operator in the expression tree
  • virtual void print (ostream s) const //
    Prints the expression associated with this binary
    node. It shouldn't modify
  • // any variables and it could be
    overridden by its sub-class
  • private
  • const char operation_ //Stores the
    operation (as a string)

13
  • //
  • //Implementation File for Binary Node Class
  • //Created by D. Schmidt and D. Levine
  • //Modified by Pradeep Vincent, 25th Feb 2001,
    Michigan State University
  • //as part of CSE 870(Advanced Software
    Engineering Course, SS01)
  • //Point of Contact Dr. Betty Cheng(chengb_at_cse.msu
    .edu)
  • //
  • include Binary_Node.h //Include Binary Node
    interface file
  • Binary_NodeBinary_Node (const char op,
  • const Tree t1,
  • const Tree t2)
  • operation_(op), left_(t1), right_(t2)
    //constructor for Binary_Node. Assigns
    operation(op) to operation_, left subtree(t1) to
    left_ and right subtree(t2) to right_
  • void Binary_Nodeprint (ostream stream) const
    //Print implementation--gt prints the left
    subtree, the operation and the right subtree in
    order
  • stream ltlt "(" ltlt this-gtleft_ // recursive
    call to print the left subtree
  • ltlt" " ltlt this-gtoperation_ // print the
    operation
  • ltlt" " ltlt this-gtright_ // recursive call--gt
    prints the right subtree
  • ltlt ")"

14
Tree Class Factory Pattern
//
//
Factory Pattern Interface File to initialize the
Node subclasses // Created by D. Schmidt and D.
Levine // Modified by Yunduan Bao, 02/25/01,
Michigan State University // as part of CSE 870
(Advanced Software Engineering Course, Sp01) //
Point of Contact Dr. Betty Cheng
(chengb_at_cse.msu.edu) //

// The factory pattern is used by
the Tree class to initialize Node
subclass TreeTree(int num) // constructor
for integer node node_( new Int_Node (num))
// initialize the value of integer
node TreeTree (const char op, const Tree t)
//constructor for a unary node node_ (new
Unary_Node (op, t)) //initialize the value of
unary node //constructor for a binary
node TreeTree (const char op, //
parameter char value of the binary node
const Tree t1, // parameter one
child of the binary node const
Tree t2) // parameter one child of the
binary node node_ (new Binary_Node (op, t1,
t2)) //initialize the value of binary node
15
Print Subtrees
King, Huang, Liu 02/25/01 Expression Tree
main()
main calls
Factory Pattern function
TreeTree() (constructor)
main calls
recursive call
Adapter Pattern function
operator ltlt ()
recursive call
Bridge Pattern function
Treeprint()
calls
Binary_Nodeprint()
Treeprint calls one of these virtual functions
Unary_Nodeprint()
Int_Nodeprint()
not recursive
Factory Pattern function
main calls
TreeTree() (destructor)
16
Main Program (main.C)
// A. Subramanian and T. Lambert //
const
Tree t1 Tree ("", Tree ("-", 5),
Tree ("", 3, 4))   // Constructs a
tree with "" as the root node. This root node
is a binary // node with two children trees. The
first child is a tree with a - as the // root
unary node and a single integer node 5. The
second child has a // root binary node with
integer nodes 3 and 4.
cout ltlt t1 ltlt endl // prints ((-5) (3
4))   // Print out the tree t1 that was just
constructed. It prints out the tree by //
calling the trees operatorltlt method. This in
turn calls the trees // print() function which
filters it down to the level of the nodes.
17
Main Program (main.C contd)
const Tree t2 Tree (, t1, t1)   //
Constructs a tree with as the root binary
node. This node has two // children which are
both the full tree t1.   cout ltlt t2 ltlt
endl   // See aforementioned comment about cout
statement.
18
Ternary.h
// A. Subramanian and T. Lambert include
Node.h   // The Ternary_Node class will inherit
from the Node class so we must // include
it.   class Ternary_Node public Node   // The
beginning of the definition of the Ternary_Node
class showing the // inheritance.   Ternary_Node
(const char , const Tree , const Tree , const
Tree )   // This is the constructor and
receives a operator as the root for the tree //
and three subtrees  
19
Ternary.h (contd incomplete)
// A. Subramanian and T. Lambert virtual void
print (ostream ) const   // This class
overloads the virtual function print from its
parent Node // class. Therefore when print is
called on a node that is a ternary node, // this
is the print method that will be
executed.   const char operation_   // This
member variable will store the operation that
will be applied to // this nodes
children.   Tree left_, middle_, right_   //
These are trees that hold the left, middle, and
right children of this // node respectively.
20
Ternary.C
  • include Ternary_Node.h
  • // Includes the class declaration for the
    Ternary_Node class.
  • Ternary_NodeTernary_Node (const char op,
  • const Tree a,
  • const Tree b,
  • const Tree c)
  • operation_ (op), left_ (a), middle_ (b),
    right_(c)

21
Ternary.C (contd)
  • // This is the implementation of the Ternary_Node
    constructor. All it
  • // does is point the member variables at the new
    values coming in.
  • void Ternary_Nodeprint (ostream stream) const
  • // The beginning of the definition of the
    Ternary_Node's print() function.
  • stream ltlt this-gtoperation_ ltlt "("
  • ltlt this-gtleft_ // recursive call
  • ltlt "," ltlt this-gtmiddle_ // recursive
    call
  • ltlt "," ltlt this-gtright_ // recursive call
  • ltlt ")"
  • // This line of code recursively prints out the
    left, middle, and right trees.

22
Sort Case Study
23
Overview of Case Study
  • Develop general purpose system sort
  • Sort lines of text from std input writes result
    to std output
  • E.g., UNIX system sort
  • External Behavior
  • line is sequence of characters terminated by
    newline
  • Default ordering is lexicographic by bytes in
    machine collating sequence
  • Constraints
  • Solution should be time/space efficient
  • (efficient I/O and memory mgmt minimal dynamic
    binding)
  • Solution should leverage/yield reusable
    components
  • (use iostreams, Array and Stack classes)
  • (yield efficient input classes, generic sort
    routines.)

24
System Sort Case Study
  • Detailed Format for Solution (p. 58)
  • Input Class (p. 61-62)
  • Implementation of Strategy Pattern (p. 73, 74)
  • Dynamic Array (p. 82)
  • Access_Table Class (p. 83) Explain how the
    3 implement the Facade and Adapter
  • Sort_AT_Adapter Class (p. 86)
  • Options Class (p. 91-92)
  • Using the Options Class (p. 93) (singleton
    pattern)
  • Using the Double-Checked Locking Optimization
    Pattern (p. 97-98)
  • Using the Bridge Pattern (p. 103)
  • Using the Factory Pattern (p. 108-109)
  • Using the Factory Method Pattern for the
    Sort_AT_Adapter (p. 114)
  • Implementing the Factory Pattern (p. 115-116)
  • Iterator Pattern (p. 118-120)

Brown, Zhu
Middlin Malinak, Post
3
Kirit, James
Hewitt, Kunath
Joy, Latif, Kalaskar
3
25
// J. Brown and F. Zhu //Prototypes template
ltclass ARRAYgt void sort (ARRAY a) // function
sort declaration void operator gtgt (istream ,
Access_TableltLine_Ptrsgt ) // override operator
gtgt void operator ltlt (ostream , const
Access_TableltLine_Ptrsgt ) // override operator
ltlt int main (int argc, char argv) //
function main // First, check if the global
options exist or are currently locked. If they
do not exist, create a // new instance of them,
then parse command line arguments. Otherwise, if
they do exist and // are not locked, parse
them. Optionsinstance ()-gtparse_args (argc,
argv) // First, check if the access table
exists or are currently locked. If it does not
exist, create a // new instance of it, then read
input into the access table. Otherwise, if it
does exist and is // not locked, read in the
input. cin gtgt System_Sortinstance()-gtaccess_tabl
e()) // First, check if the access table is
locked. If not, sort the line of text. sort
(System_Sortinstance()-gtaccess_table()) //
First, check if the access table is locked. If
not, output the sort result from the access
table. cout ltlt System_Sortinstance ()
-gtaccess_table()
26
//
// Input class stream input, read a
whole file , Created by D. Schmidt and D.
Levine // Modified by Feng Zhu, Jack Brown,
02/25/01, Michigan State University // as part of
CSE 870 (Advanced Software Engineering Course,
Sp01) // Point of Contact Dr. Betty Cheng
(chengb_at_cse.msu.edu) //
class Input //
Describes the Input class public // Reads
from ltinputgt up to ltterminatorgt, replacing
ltsearchgt with ltreplacegt. // Returns pointer to
dynamically allocated buffer. char read
(istream input, int terminator EOF, int
search '\n', int replace '\0') // Number
of bytes replaced. size_t replaced (void)
const // Size of buffer size_t size (void)
const private // Recursive helper
method. char recursive_read (void)
27
//
// Sort function Strategy pattern, allow
different pivot selection // Created by D.
Schmidt and D. Levine // Modified by Feng Zhu,
Jack Brown, 02/25/01, Michigan State
University // as part of CSE 870 (Advanced
Software Engineering Course, Sp01) // Point of
Contact Dr. Betty Cheng (chengb_at_cse.msu.edu) //

template ltclass ARRAYgt //function template,
allow different array of data to be sorted void
sort (ARRAY array) // function sort, doing quick
sort // First, check if the pivot strategy
exists or is currently locked. // If it does
not exist, create a new instance of it, then find
a pivot // value into the access table.
Otherwise, if it does exist and is // not
locked, find a pivot value. PivotltARRAYgt
pivot_strat PivotltARRAYgtmake_pivot (Options
instance ()-gtpivot_strat()) quick_sort
(array, pivot_strat) // call quick_sort to sort
the data
28
//
// quick_sort function select a pivot and
sort // Created by D. Schmidt and D. Levine //
Modified by Feng Zhu, Jack Brown, 02/25/01,
Michigan State University // as part of CSE 870
(Advanced Software Engineering Course, Sp01) //
Point of Contact Dr. Betty Cheng
(chengb_at_cse.msu.edu) //
// function
template, allow different array of date to be
sorted and // correspondent pivot strategy
passed in template ltclass ARRAY, class
PIVOT_STRATgt quick_sort (ARRAY array,
PIVOT_STRAT pivot_strat) // function
quick_sort // Loop until.... for ()
ARRAYTYPE pivot // typename ARRAYTYPE
pivot ... // Get the pivot using the pivot
strategy pivot pivot_strat-gtget_pivot
(array, lo, hi) // Partition arraylo, hi
relative to pivot ...
29
Explanation of Facade and Adapter Patterns
  • M. Malinak, P. Middlin, R. Post, J. Babbage
  • Facade Intent
  • Provide a unified interface to a set of
    interfaces in a subsystem
  • Façade defines a higher-level interface that
    makes the subsystem easier to use
  • Adapter Intent
  • Convert the interface of a class into another
    interface clients expect
  • Adapter lets classes work together that couldnt
    otherwise because of incompatible interfaces

30
Dynamic Array
  • // The Array class is the low-level
    implementation of the data storage. It
  • // is hidden from the Sort class in multiple
    levels- the Access_Table class
  • // makes use of the Array class to store what
    needs to be stored from input.
  • // The Sort_AT_Adapter class then provides the
    adaptation between the Sort
  • // and Access_Table classes.
  • template ltclass Tgt // Templated class
    definition for Array
  • class Array
  • // interfaces available to other classes
  • public
  • Array (size_t size 0) // Constructor
  • int init (size_t size) // initialize size
    with given size argument

31
Dynamic Array (cont.)
  • T operator(size_t index) // returns object
    given index
  • // Using operators
    instead of function
  • // calls is a
    convenience issue. This is the
  • // facade pattern.
  • size_t size (void) const // returns current
    size of array
  • // . . .
  • // interfaces exclusive to this class
  • private
  • T array_ // a pointer to a
    single object
  • size_t size_ // the current size of
    the array

32
The Access_Table Class
  • // The Access_Table class makes use of the Array
    class to store its input.
  • // The function calls for using the Access_Table
    class are not the same
  • // as the function calls that The Sort class
    expects to use, this Access_Table
  • // class will be adapted using the
    Sort_AT_Adapter class. This class uses
  • // some Adapter pattern ideas, in that it hides
    the indexing call
  • // to the access_array_ variable with a function
    called element(index).
  • template ltclass Tgt // Templated class
    definition for Access_Table
  • class Access_Table
  • // interfaces available to other classes
  • public
  • // Factory Method for initializing
    Access_Table.
  • virtual int make_table (size_t num_lines,
  • Char buffer) 0

33
The Access_Table Class (cont)
  • // Destructor
  • // Release buffer memory.
  • virtual Access_Table (void) delete
    buffer_
  • // Retrieve reference to ltindexthgt element.
  • T element (size_t index)
  • return access_array_index // passes call
    to the underlying Array object
  • // Length of the access_array.
  • size_t length (void) const
  • return access_array_.size () // passes call
    to the underlying array

34
The Access_Table Class (cont)
  • // interfaces available only to this class and
    classes derived from it
  • protected
  • ArrayltTgt access_array_ // Access table is
    array of type T.
  • char buffer_ // Hold the data
    buffer.

35
The Sort_AT_Adapter Class
  • // The Sort_AT_Adapter class is an intermediary
    adapter class that translates
  • // the calls that the Sort class would make into
    the appropriate calls
  • // for the Access_Table class. The calls the Sort
    class makes are standard
  • // for that class, and we shouldn't have to be
    aware of how the Acess_Table
  • // class works in the Sort class. Instead, we
    adapt the Access_Table class
  • // to the Sort class by making an additional
    class that calls the appropriate
  • // functions between classes. This way two
    classes can communicate with
  • // one another when they otherwise could not.
  • // Low level detail we use this struct for
    storing pointers to the actual
  • // data
  • struct Line_Ptrs
  • // Comparison operator used by sort().
  • int operatorlt (const Line_Ptrs )

36
The Sort_AT_Adapter Class (cont)
  • // beginning of line and field/column.
  • char bol_, bof_
  • class Sort_AT_Adapter
  • // Note the use of the class form of the
    Adapter
  • private Access_TableltLine_Ptrsgt
  • // interfaces available to other classes
  • public
  • // creates the table of data
  • virtual int make_table (size_t num_lines, char
    buffer)
  • typedef Line_Ptrs TYPE // Type trait.

37
The Sort_AT_Adapter Class (cont)
  • // These methods adapt Access_Table methods
  • // The indexing () operator is used to access
    a given index.
  • // We translate this into the actual function
    call that gets
  • // and indexed value, which is may not be in a
    simple indexable
  • // array at all. This is the Facade pattern -
    we hide the actual
  • // implementation with a simpler, easier to use
    operator.
  • T operator (size_t index)
  • return element (index)
  • // The size function is what the Sort class
    expects to call.
  • // This is translated to the "length" function
    of the Access_Table
  • // class.
  • size_t size (void) const return length ()

38
Options.h(Singleton Pattern)
  • By
  • Kirit Patel
  • James Vanderhyde

39
Why use Singleton Patterns?
  • Ensures a class has only one instance.
  • Providing a global point of access to it.
  • Sometimes we want to make sure that there is only
    one instance of a particular class/system. (i.e.
    file system, window manager,)
  • Singleton was a nice person.

40
Options.h
  • //This class is a Singleton. It contains exactly
  • // one instance that is statically referenced.
  • // It is useful for holding global information
  • // without the dangers of global variables.
  • class Options
  • public // interfaces available to other
    classes
  • //Returns a pointer to the singleton object
    of this class
  • static Options instance (void)
  • //Parses and stores options from main
  • void parse_args (int argc, char argv)

41
Options.h (Contd.)
  • //Four options that may be on or off
  • //These options are stored in octal order
  • // so that we can use them as bitmasks!
  • enum Option
  • FOLD 01, //compare strings case insensitively
  • NUMERIC 02, //compare string as if numbers
  • REVERSE 04, //sort in reverse order (?)
  • NORMAL 010 //compare strings case
    senstively
  • //Pivot-selection strategy for quicksort
  • enum Pivot_Strategy
  • MEDIAN, //median of first, middle, and last
  • RANDOM, //randomly choose a pivot
  • FIRST //use first element

42
Options.h (contd.)
  • //Returns whether Option o is set in this
    singleton
  • bool enabled (Option o)
  • //Returns value of a global variable for
  • // how far we have progressed through the
    input
  • int field_offset (void) // Offset from BOL.
  • //Returns the pivot strategy in this
    singleton
  • Pivot_Strategy pivot_strat (void)
  • //Function pointer for comparing two strings
  • int (compare) (const char l, const char
    r)

43
Options.h (Contd.)
  • protected //interfaces available to this class
    and classes derived from it
  • //The default constructor for this class
  • //I don't know how it ensures a singleton.
  • Options (void) // Ensure Singleton.
  • //The place the maskable options are stored
  • u_long options_ //Maintains options bitmask
    . . .
  • //How far we have progresses through the
    input
  • int field_offset_
  • //The single instance of the class
  • //Since it's static, it is referenced through
    the class
  • static Options instance_ // Singleton.

44
Options.h (Contd.)
  • //This operator is used to compare two Line_Ptrs
    objects.
  • int Line_Ptrsoperatorlt (const Line_Ptrs rhs)
  • //Get a handy reference to the global
    information.
  • Options options Optionsinstance ()
  • //If we are under normal operation,
  • if (options-gtenabled (OptionsNORMAL))
  • //we compare with strcmp.
  • return strcmp (this-gtbof_, rhs.bof_) lt 0
  • //Otherwise, if we are under case-insensitive
    operation,
  • else if (options-gtenabled (OptionsFOLD))
  • //we compare with strcasecmp.
  • return strcasecmp (this-gtbof_, rhs.bof_) lt 0

45
Options.h (Final)
  • //Otherwise, we must be under number comparing
    operation,
  • else
  • // assert (options-gtenabled (OptionsNUMERIC))
  • //so we use numcp.
  • return numcmp (this-gtbof_, rhs.bof_) lt 0

46
//TEMPLATE Singleton is a generic templated
class independent // of a particular
type. TYPE and LOCK, are the data //
types to use when a Singleton object is
instantiated. //PURPOSE we need to ensure only
one instance of the singleton // object
is created. we use a singleton pattern and a //
double checking lock mechanism to
eliminate race // conditions that may
occur in a multi-threaded environment. template
ltclass TYPE, class LOCKgt class Singleton public
//member function instance created
once(static) and remains //until program
completion static TYPE instance
(void) protected //pointer to unique instance
that remains for entire program static TYPE
instance_ static LOCK lock_ //locking
mechanism
47
  • //TEMPLATE TYPE and LOCK, the data types to use
    when Singleton
  • // is called.
  • //RETURN pointer to single instance of object
    TYPE
  • //PURPOSE hide creation of object and provide
    access to instance
  • // behind class operation so that the class
    cannot be
  • // instantiated more than once or
    directly
  • template ltclass TYPE, class LOCKgt
  • TYPE
  • SingletonltTYPE, LOCKgtinstance (void)
  • //checks if we already have an instance
  • if (instance_ 0)
  • //locks only on first access to eliminate race
    conditions
  • //and lock overhead
  • GuardltLOCKgt mon (lock_)
  • if (instance_ 0) //double check
  • instance_ new TYPE //create new instance
  • return instance_

48
  • //PURPOSE operator lt used to perform sort. we
    use a bridge pattern
  • // to decouple the comparison operation
    from the implementation
  • // by providing the Line_Ptrs interface
    and calling the
  • // Optionscompare member function to
    handle the specific
  • // comparison.
  • //INPUT reference to right hand operand.
  • //COMMENTS dereferences rhs, a variable declared
    as data member of
  • // Line_Ptrs
  • int
  • Line_Ptrsoperatorlt(const Line_Ptrs rhs)
  • //operator lt relies on the return value
    determined by
  • //Optionscompare
  • return (Optionsinstance ()-gtcompare)
  • (bof_, rhs.bof_) //this-gtbof_ltrhs.bof_

49
CSE870 Homework 5Design Pattern Case Studies
with C
  • by
  • Rajat Joy
  • Rahul Kalaskar
  • Amal Latif
  • Prakarn Unachak

50
pg. 108
  • /
  • Options this class contains the cmd line
    options parse_args method used
  • to assign value to the function ptr compare
  • /
  • Options parse_args (int argc, char argv)
  • // . . .
  • if (this-gtenabled (Options NORMAL)) // check
    if the cmd line option is // NORMAL
  • this-gtcompare strcmp // assign addr of
    strcmp to compare
  • else if (this-gtenabled (Options FOLD)) //
    check if the cmd line option is // FOLD
  • this-gtcompare strcasecmp // assign addr of
    strcmp to compare
  • else if (this-gtenabled (Options NUMERIC)) //
    check if the cmd line option is // NUMERIC
  • this-gtcompare numcmp // assign addr of
    strcmp to compare
  • // . . .

51
pg. 109
  • / This method implements the numeric
    comparison s1 and s2 are strings /int
    numcmp (const char s1, const char
    s2) double d1 strtod (s1, 0), d2 strtod
    (s2, 0)
  • // strtod gt sting to double if (d1 lt d2)
    return -1 // if d1 is less than
    d2 return
  • // -1 else if (d1 gt d2) return 1
    // if d1 is greater than d2
  • // return 1 else // if (d1 d2)
    return 0 // return 0 for all other case

52
pg. 114
  • /
  • This method is used to read and initialize
    Access table is input stream at Access table
  • /
  • template ltclass Tgtvoid operatorgtgt (istream is,
    Access_Tablelt Tgt at) Input input // class
    used to read the text char buffer
    input.read (is) // Read entire stdin into
    buffer. size_t num_lines input.replaced () //
    gives the no. of line of text. at.make_table
    (num_lines, buffer) // Factory Method
    initializes // Access_ Tableltgt.

53
pg. 115
  • / Factory Method initializes Access_ Table.
    num_lines no of lines in the text buffer
    contains the text /int Sort_AT_Adapter
    make_table (size_t num_lines, char buffer) //
    Array assignment op. this-gtaccess_array_.resize
    (num_lines) // resize access array according
    // to the new no. of line (resize //
    needs to be defined in // Sort_AT_Adaptor)
  • this-gtbuffer_ buffer // Obtain
    ownership. size_t count 0 //initialize the
    counter.

54
pg. 116
  • // Iterate through the buffer and determine where
    the beginning of lines and fields
  • // must go.
  • // Line_Ptrs-Iter gives on line at a time. The
    line is then assigned in the
  • // access_array
  • for (Line_Ptrs_Iter iter (buffer, num_lines)
    iter.is_done () 0 iter.next ())
  • Line_Ptrs line_ptr iter.current_element ()
    // get the current line // from the iter.
  • this-gtaccess_array_ count line_ptr //
    assign this line to // the current
    // position in the // access
    array.

55
pg. 118
  • /
  • Constructor for Line_Ptr_Iter class buffer
    buffer containing
  • the lines
  • num_lines no. of line in the buffer
  • /
  • Line_Ptrs_Iter Line_Ptrs_Iter(char buffer,
    size_t num_lines)

56
pg 119
  • /
  • This method gets the current element in the
    iter returns the ptr to Line_Ptrs
  • /
  • Line_Ptrs Line_Ptrs_Iter current_element (void)
  • Line_Ptrs lp //lp is a data structure of type
    Line_Ptrs // Determine beginning of next line
    and next field ... lp.bol_ // . . . // assigns
    a ptr lp.bof_ // . . . // assigns a
    ptr return lp

57
pg. 120
  • /
  • Out the text depending upon the options.
  • os is the output stream at is the access table.
  • /
  • template ltclass Tgt
  • void operatorltlt (ostream os,const Access_Tablelt
    Tgt at)
  • if (Options instance()-gtenabled
    (OptionsREVERSE))
  • // check for options.
  • for (size_t i at.size() i gt 0 -- i) // if
    the option is REVERSE, os ltlt at i - 1 //
    display the access table from // last to
    first Array entryelse for (size_t i 0 i lt
    at.size() i) // if not, display the access
    table os ltlt ati // from first Array entry
    to the // last
Write a Comment
User Comments (0)
About PowerShow.com