IMP  2.0.1
The Integrative Modeling Platform
ExampleDecorator.h
Go to the documentation of this file.
1 /**
2  * \file IMP/example/ExampleDecorator.h \brief Add a name to a particle.
3  *
4  * Copyright 2007-2013 IMP Inventors. All rights reserved.
5  *
6  */
7 
8 #ifndef IMPEXAMPLE_EXAMPLE_DECORATOR_H
9 #define IMPEXAMPLE_EXAMPLE_DECORATOR_H
10 
11 #include <IMP/example/example_config.h>
12 
13 #include <IMP/Particle.h>
14 #include <IMP/Model.h>
15 #include <IMP/Decorator.h>
16 #include <IMP/decorator_macros.h>
17 #include <IMP/exception.h>
18 
19 IMPEXAMPLE_BEGIN_NAMESPACE
20 
21 //! A simple decorator which adds a name to a particle.
22 /** A decorator adds functionality to a particle and ensures that invariants
23  are preserved. In this case, the functionality is the setting and access
24  of a name for the Particle and the invariant is that the name is always
25  non-empty.
26 
27  The source code is as follows:
28  \include ExampleDecorator.h
29  \include ExampleDecorator.cpp
30 */
31 class IMPEXAMPLEEXPORT ExampleDecorator: public Decorator
32 {
33  /* Use a static variable in a static method to create the key
34  so that it is only done once and is only done when it is first
35  needed. Lazy initialization of keys makes \imp more efficient as
36  Particles do not have to allocate memory for ununsed keys.
37  */
38  static StringKey get_name_key();
39 
40 public:
41 
42  //! Add a name to the particle
43  /** The create function should take arguments which allow
44  the initial state of the Decorator to be reasonable (i.e.
45  make sure there is a non-empty name).
46  */
47  static ExampleDecorator setup_particle(Particle *p, std::string name) {
48  // use the object check macro to check that the particle is valid
50  // use the usage check macro to make sure that arguments are correct
51  IMP_USAGE_CHECK(!name.empty(), "The name cannot be empty.");
52  p->add_attribute(get_name_key(), name);
53  ExampleDecorator ret(p);
54  return ret;
55  }
56 
57  //! return true if the particle has a name
58  static bool particle_is_instance(Particle *p) {
59  return p->has_attribute(get_name_key());
60  }
61 
62  //! Get the name added to the particle
63  std::string get_decorator_name() const {
64  return get_particle()->get_value(get_name_key());
65  }
66 
67  //! Set the name added to the particle
68  void set_decorator_name(std::string nm) {
69  // use the usage check macro to check that functions are called properly
70  IMP_USAGE_CHECK(!nm.empty(), "The name cannot be empty");
71  get_particle()->set_value(get_name_key(), nm);
72  }
73 
74 
75  /* Declare the basic constructors and the cast function.*/
77 };
78 
79 
80 /** Define a collection of them. Also look at example.i*/
81 IMP_DECORATORS(ExampleDecorator, ExampleDecorators, Particles);
82 
83 IMPEXAMPLE_END_NAMESPACE
84 
85 #endif /* IMPEXAMPLE_EXAMPLE_DECORATOR_H */