1. Trang chủ
  2. » Kỹ Thuật - Công Nghệ

CRC.Press A Guide to MATLAB Object Oriented Programming May.2007 Episode 2 Part 5 potx

20 337 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 20
Dung lượng 1,3 MB

Nội dung

254 A Guide to MATLAB Object-Oriented Programming exercise of entering private variables in §18.1.2, the fields Name and Comment are familiar. The type, accessor, and mutator fields are new. The type field serves two purposes. First, with the exception of display, the public name and its type string are copied into all group-of-eight headers. Second, the type string is displayed as a hint when set is called with one argument. That also means the type string is copied into the –possible case inside fieldnames. Accessor Expression and Mutator Expression fields guide the generation of public cases inside get.m and set.m. If the Expression field contains the name of a private variable, direct-access code syntax will be inserted into get or set. If the Expression field contains the string %helper, helper-function syntax will be inserted into get or set, and a stub for the helper will be generated. Finally, if the Expression field is empty, a public case for the variable is not included. The Accessor Expression value and Mutator Expression value are independent. Accessor Expression influences the code in get and Mutator Expression influences the code in set. In addition, public variables with an empty Accessor Expression value are not included in fieldnames or struct. All public variables in cLineStyle have accessors. The accessor for Color uses a helper, but accessors for LineWidth and LineHandle are directly linked to mLineWidth and mLineHandle. All public variables also have mutators. In this case, the mutator for LineWidth is not a direct link but rather uses a helper. The table of entries for the public variables is given in Table 18.2. The procedure for data entry follows the same procedure used for private variables. Select the first empty line in the lower display block, and enter data in the fields. After all field values have been specified, click Save Change to commit the data and move to the next line. In this dialog, the lower display can’t be easily formatted using standard MATLAB syntax. Instead, the lower display delimits each field by putting two colons between each value. The display order is name, type, accessor, mutator, and comment. When you have finished all additions or modifications, click Done to commit the changes and return to the main dialog. FIGURE 18.4 Class Wizard, cLineStyle public variable dialog. C911X_C018.fm Page 254 Friday, March 2, 2007 9:06 AM Class Wizard Versions of the Shape Hierarchy 255 If you compare the generated group-of-eight files with files from Chapter 16, the code lines are identical. Because of this, you will have no trouble relating the code to discussions in the previous chapters. Ideally, you will never need to hand tailor any function in the group of eight, but if do, you should have no trouble finding your way. Accessor and mutator helper functions are another matter. These private functions require tailoring because the dialog data do not include any information that could be used to generate class-specific code. The functions include header information and they include code stubs that allow them to work without error. This allows group-of-eight mechanics to be tested prior to tailoring, but the class is not fully functional until afterward. We revisit the topic of helper file tailoring in §18.1.7. 18.1.4 CLINESTYLE CONSTRUCTOR FUNCTIONS The final data-entry button on the main dialog defines constructors. The cLineStyle class uses a two-argument constructor to assign values for Color and LineWidth. Click the Construc- tors button to display the dialog shown in Figure 18.5. To define a new constructor, the TABLE 18.2 cLineStyle Public Member Variable Field Values Public Variable Name Type Accessor Expression Mutator Expression Comment Color (3x1) array %helper %helper RGB line color LineWidth integer > 0 mLineWidth %helper LineHandle graphics handle mLineHandle mLineHandle Public graphics handle to the line plot FIGURE 18.5 Class Wizard, cLineStyle constructor function dialog. C911X_C018.fm Page 255 Friday, March 2, 2007 9:06 AM 256 A Guide to MATLAB Object-Oriented Programming only data required are a comma-separated list of input variable names. The function name is created based on the number of variables. The comma-separated variable list is entered in the Input Argument List field. Any valid variable name except this can be used in the list. For this example, we don’t need a table of dialog values. Select the first empty line in the lower display. Then type color, width into the Input Argument List field. When you are done, click Save Change to commit the data. Finally, click Done to return to the main dialog. During file generation, Class Wizard will use this data to generate a function stub named private/ctor_2.m. The stub contents are shown in Code Listing 106. The comma-separated list from the definition data shows up in the input argument list of the function definition. These variable names also show up in the header on lines 12 and 14. The comments list them as having no type info and no description because data dictionary data for these variables do not yet exist. The generated code is found in lines 27–31. The function will run; however, until it is tailored, line 29 will display a warning. The helper can be tailored by copying code from the Chapter 16 version. Code Listing 106, Two-Input Class Wizard Constructor, @cLineStyle/private/ctor_2.m function this = ctor_2(this, color, width) 1 function this = ctor_2(this, color, width) 2 %CTOR_2 for class cLineStyle, Replace with a short note 3 % Replace with something like UNCLASSIFIED 4% 5 % function this = ctor_2(this, color, width) 6% 7 % Replace with text that you would like to have copied into the header of 8 % every file in this class 9% 10 % Input Arguments:: 11 % 12 % color: no type info: no description provided 13 % 14 % width: no type info: no description provided 15 % 16 % Author Info 17 % Replace with your company's name 18 % Replace with your name 19 % Replace with your email address 20 % Replace with your phone number 21 % Replace with the author notes that you would like to appear just after 22 % the author info for every file in this class 23 % Replace with your standard copyright notice 24 % Replace with a string recognized by your revision control software 25 % A Class Wizard v.3 assembled file, generated: 20-Dec-2005 13:23:23 26 C911X_C018.fm Page 256 Friday, March 2, 2007 9:06 AM Class Wizard Versions of the Shape Hierarchy 257 18.1.5 CLINESTYLE DATA DICTIONARY At this point in the definition, public and private variables are defined and an additional constructor is available. From the main screen, you could generate all required files for a fully functioning cLineStyle class. But don’t click Build Class Files because there is one more dialog that needs attention. We need to add comments so the header inside ctor_2 will contain mean- ingful comments for its input arguments. On the menu bar of the main dialog, select Data::Dictionary …. This selection will display the dialog shown in Figure 18.6. These fields are similar to the same fields in the public variable dialog. Initially the lower display should include the variable names color and width but there will be no type or comments. The variable names in the lower display were collected from the argument definitions used to define constructors, public functions, and private functions. Since cLineStyle uses the standard set of public and private functions, the list only includes constructor arguments. The data dictionary dialog can’t be used to add variables. Variables are added automatically based on function definitions. The type and comment data you need are provided in Table 18.3. Select each variable by pointing to its line in the lower display and clicking. The field values are now active and can be modified. Click Save Change to commit the changes before selecting the next name. After entering all the data, click Done to return to the main dialog. Now if you generate the files, the header in ctor_2 will contain meaningful comments. The affected lines now look like the following: 27 % \/ \/ \/ \/ 28 % replace with your specific constructor code 29 warning('OOP:incompleteFunction', 30 'The function definition is incomplete'); 31 % /\ /\ /\ /\ 32 % Replace with something like UNCLASSIFIED FIGURE 18.6 Class Wizard, cLineStyle data dictionary dialog. C911X_C018.fm Page 257 Friday, March 2, 2007 9:06 AM 258 A Guide to MATLAB Object-Oriented Programming % Input Arguments:: % % color: 3x1 RGB values 0-1: The initial RGB line color. The % array is a 3x1 column vector of values and the values % range from zero to one. % % width: integer > 0: The initial line width as an integer % greater than 0 18.1.6 CLINESTYLE BUILD CLASS FILES The definition for cLineStyle is now complete. Click Build Class Files to begin class file generation. You always need to specify a destination class directory. MATLAB’s standard directory-selection dialog is used. An example of the dialog is shown in Figure 18.7. Simply highlight the desired directory and click OK. If a suitable directory does not exist, the Make New Folder button on the lower left will allow you to create one. When you click OK, Class Wizard TABLE 18.3 cLineStyle Data Dictionary Field Values Variable Name Type Comment color 3x1 RGB values 0-1 The initial RGB line color. The array is a 3x1 column vector of values and the values range from zero to one. width integer > 0 The initial line width as an integer greater than 0 FIGURE 18.7 Class Wizard, cLineStyle directory-selection dialog. C911X_C018.fm Page 258 Friday, March 2, 2007 9:06 AM Class Wizard Versions of the Shape Hierarchy 259 generates class files. File generation is very fast. Click Okay on the confirmation dialog to return to the main Class Wizard dialog. The newly generated class should work without error; however, a couple of helper functions need to be tailored before the class will achieve full functionality. These functions are discussed next. 18.1.7 CLINESTYLE ACCESSOR AND MUTATOR HELPER FUNCTIONS In cLineStyle three private helper functions need to be tailored. The first is ctor_2, a private constructor helper. The as-generated file was shown in Code Listing 106. Modifying the as- generated file is easy because we can copy the code body from the working version in Chapter 16. Refer to Code Listing 89 to see the complete function body. Code bodies for the other two helpers, Color_helper and LineWidth_helper, can also be copied from Chapter 16. After copying the code bodies, cLineStyle is complete. The tailored versions of Color_helper and LineWidth_helper are also included in this chapter’s source files. Before moving to the other classes, let’s look at the initial helper-file stub. The as-generated version of Color_helper is shown in Code Listing 107. The listing consists mostly of comments, but there are some important lines of code in each case. Code Listing 107, Public Variable Helper, as Generated by Class Wizard, cLineStyle::Color_helper 1 function [do_sub_indexing, do_assignin, this, varargout] = 2 Color_helper(which, this, index, varargin) 3 %COLOR_HELPER for class cLineStyle, Replace with a short note 4 % Replace with something like UNCLASSIFIED 5% 6 % function [do_sub_indexing, do_assignin, this, varargout] = 7 % Color_helper(which, this, index, varargin) 8% 9 % Replace with text that you would like to have copied into the header 10 % of every file in this class 11 % 12 % Author Info 13 % Replace with your company's name 14 % Replace with your name 15 % Replace with your email address 16 % Replace with your phone number 17 % Replace with the author notes that you would like to appear just 18 % after the author info for every file in this class 19 % Replace with your standard copyright notice 20 % Replace this line with a string for your revision control software 21 % A Class Wizard v.3 assembled file, generated: 18-Jan-2006 13:18:46 C911X_C018.fm Page 259 Friday, March 2, 2007 9:06 AM 260 A Guide to MATLAB Object-Oriented Programming 22 % 23 24 switch which 25 case 'get' % ACCESSOR 26 % input: index contains any additional indexing as a substruct 27 % input: varargin empty for accessor 28 do_sub_indexing = true; % tells get.m whether to index deeper 29 do_assignin = false; % leave false until you read book section 3 30 varargout = cell(1, nargout-3); % -3, 3 known vars plus varargout 31 % \/ \/ \/ \/ 32 % YOUR 'GET/ACCESSOR' HELPER CODE GOES HERE 33 % e.g., [varargout{:}] = {function of public and private vars}; 34 warning('OOP:incompleteFunction', 35 'The function definition is incomplete'); 36 % /\ /\ /\ /\ 37 case 'set' % MUTATOR 38 % input: index contains any additional indexing as a substruct 39 % input: varargin contains values to be assigned into the object 40 do_sub_indexing = false; % always false, mutator _must_ index 41 do_assignin = false; % leave false until you read book section 3 42 varargout = {}; % 'set' returns nothing in varargout 43 % \/ \/ \/ \/ 44 % YOUR 'SET/MUTATOR' HELPER CODE GOES HERE 45 warning('OOP:incompleteFunction', 46 'The function definition is incomplete'); 47 % below is a code template as a convenient starting point 48 % if isempty(index) % No more indexing requested, assign input 49 % [this.Color] = deal(varargin{:}); 50 % else % deeper indexing requested, use subsasgn to do it 51 % Color = [this.Color]; % Modify the assignment 52 % Color = subsasgn(Color, index, varargin{:}); 53 % [this.Color] = Color; 54 % end 55 % /\ /\ /\ /\ 56 otherwise 57 error('OOP:unsupportedOption', ['Unknown helper option: ' which]); C911X_C018.fm Page 260 Friday, March 2, 2007 9:06 AM Class Wizard Versions of the Shape Hierarchy 261 Lines 25–36 contain the placeholder for tailored accessor code. Lines 28–29 assign typical flag values, and line 30 preallocates varargout based on the size of nargout. These three lines are usually necessary so they are automatically included. Lines 31–36 should be replaced by helper- specific accessor code. Otherwise, lines 34–35 will generate a warning and return empty values. If accessor syntax is direct-link, there are two options depending on how much control is desired. Either leave the warning in place or replace the warning with direct-link code. Lines 37–55 contain the placeholder for tailored mutator code. Lines 40–41 assign typical flag values, and line 42 preallocates varargout. Note that the mutator code must either use all the index values or throw an error. Here varargout is empty because the object is returned in the output variable this. These three lines are usually necessary so they are automatically included. Lines 43–55 should be replaced by helper-specific mutator code. Otherwise, lines 45–46 will generate a warning and an unmodified this will be returned. The comments in lines 48–54 represent typical direct-link syntax and are included as an aid to development. 18.2 CSHAPE CLASS WIZARD DEFINITION DATA Data entry for every class follows the same procedure used to define cLineStyle. During the definition of cShape, we will build on that procedure by spending more time discussing new areas. Open a new session of Class Wizard or select File::New from the menu and type in cShape as the class name. From an earlier chapter, we know that cShape needs to be superior to double. In the Superior To: field on the main dialog, add the string double. If cShape needed to be superior to more than one type, a comma-separated list would be used. Keep the default values for all other main dialog data. The remaining definition data are entered using the various data-entry dialogs. 18.2.1 CSHAPE HEADER INFO Click the Header Info … button and select Default Header Info::Load from the menu. This selection loads the collection of default values previously saved during the definition of cLine- Style. You can change the field values or leave them as is. Click Okay to return to the main dialog. 18.2.2 CSHAPE PRIVATE VARIABLES The next dialog for data entry defines the class’ private variables. Click the Private Variables … button and enter the data shown in Figure 18.8. The data are also summarized in Table 18.4. Data entry is the same as before. First, select an empty line in the lower display block and start entering private variable data. Click Save Change to commit the changes and move to the next line. Finally, when data for all variables have been saved, click Done to return to the main dialog. The only noteworthy aspects of the private variables are the initial values. The initial mPoints array is now defined to be empty. Previous versions of cShape used the corner points of a star to populate mPoints. If you prefer star corner points, modify the initial value field for mPoints and rebuild the class. The initial value for mLineStyle calls the cLineStyle constructor using two arguments. This is an example of composition and demonstrates how easy it is to define a class that uses composition. Except for comments, the version of /@cShape/pri- vate/ctor_ini resulting from the private variable definitions is identical to the Chapter 16 version. This fi le and all the class fi les for this chapter can be found in /oop_guide/chapter_18. 58 end 59 % Replace with something like UNCLASSIFIED C911X_C018.fm Page 261 Friday, March 2, 2007 9:06 AM 262 A Guide to MATLAB Object-Oriented Programming 18.2.3 CSHAPE CONCEALED VARIABLES Moving down the collection of dialog buttons brings us to the concealed variables button. Click the Concealed Variables … button and enter the data shown in Figure 18.9. The concealed variable data are also provided in Table 18.5. Fields for concealed variables are the same as the fields for public variables because there is very little difference between the two. In the generated functions, concealed variables are written into the concealed variable sections of get and set. If you examine these files, you will notice that the mFigureHandle shares the concealed section with another concealed variable, mDisplayFunc. Managed exclusively by Class Wizard, mDis- playFunc should never be included in the concealed variable dialog. When you are finished, click Done to return to the main dialog. FIGURE 18.8 Class Wizard, cShape private variable dialog. TABLE 18.4 cShape Private Variable Dialog Fields Private Variable Name Initial Value Comment mSize ones(2,1) Scaled [width; height] of bounding box mScale ones(2,1) [width; height] scale factor mPoints zeros(2,0) Columns of [x; y] shape corner values mFigureHandle [] Handle for the shape’s figure window mLineStyle cLineStyle ([0;0;1], 1) Secondary cLineStyle object C911X_C018.fm Page 262 Friday, March 2, 2007 9:06 AM Class Wizard Versions of the Shape Hierarchy 263 18.2.4 CSHAPE PUBLIC VARIABLES The next move down the collection of dialog buttons brings us to the public variables button. Click the Public Variables … button and enter the data shown in Figure 18.10. The public variable data are also provided in Table 18.6. When you are finished, click Done to return to the main dialog. All public variables defined for cShape have accessors. Accessors for Size and Points use simple, direct-link syntax, and accessors for ColorRgb and LineWeight use a helper function. Internally, cShape manages color and line width through a secondary object stored in mLineStyle. Access to the color value is simple, but it does not conform to direct-link require- ments. Consequently, ColorRgb must specify helper-function syntax. Access to the line width is more complicated because the interface converts between strings ‘normal’ and ‘bold’ and integer width values. All public variables defined for cShape also have mutators. In this case, the desire for a robust interface complete with input value checking means that all public variables use helper function syntax for mutation. Helper-function stubs all look similar to the Color_helper stub in Code Listing 107. The appropriate helper-function code for cShape’s private variables was developed in Chapter 16. FIGURE 18.9 Class Wizard, cShape concealed variable dialog. TABLE 18.5 cShape Concealed Variable Dialog Fields Concealed Variable Name Type Accessor Expression Mutator Expression Comment mFigureHandle graphics handle mFigureHandle The shape’s handle- graphics handle C911X_C018.fm Page 263 Friday, March 2, 2007 9:06 AM [...]... many arguments are in the input list In response to the parent data, Class Wizard will generate a parent_list function that returns a cellstr populated with parent-class values After entering cShape parent data, click Save Change to commit the data Click Done to return to the main dialog FIGURE 18.14 Class Wizard, cStar parents dialog C911X_C018.fm Page 26 9 Friday, March 2, 20 07 9:06 AM Class Wizard... child-class cStar adds a title to the figure window where the shape is plotted To do this, mTitle is added as a private variable and Title is added as a public variable To add the correct private variable, start at the main dialog Click the Private Variables … button and enter the data provided in Table 18.9 After entering the data, click Save Changes and Done This will commit the data and return you to. .. field value consists of a 2 × n array of corner points The default points for cStar line on the unit circle, and a complex exponential is one easy way to generate the values When arrays are used as initial values, don’t add commas to separate elements in the array MATLAB can delimit array elements using a comma or a space If you use a comma, Class Wizard will get confused because it counts commas to determine... labeled Data::Dictionary … Enter the data shown in Table 18. 12 into the data dictionary dialog After entering the data, click Save Changes and Done to return to the main dialog TABLE 18.10 cStar Public Variable Data Public Variable Name Title Type Accessor Expression Mutator Expression string mTitle %helper Comment A title for the figure window C911X_C018.fm Page 27 0 Friday, March 2, 20 07 9:06 AM 27 0... detailed in Table 18.13 The table includes an accounting of all the member functions All the functions executed during the draw command above have a gray background The members of cDiamond are not exercised because there are no cDiamond objects involved in the command C911X_C018.fm Page 27 2 Friday, March 2, 20 07 9:06 AM 27 2 A Guide to MATLAB Object- Oriented Programming FIGURE 18. 15 A double blue star...C911X_C018.fm Page 26 4 Friday, March 2, 20 07 9:06 AM 26 4 A Guide to MATLAB Object- Oriented Programming FIGURE 18.10 Class Wizard, cShape public variable dialog TABLE 18.6 Public Member Variable Field Values Public Variable Name Type Accessor Expression Mutator Expression Size double array (2x1) mSize %helper ColorRgb double array (3x1) double array (2xN) %helper %helper %helper %helper normal, bold %helper... realize all the things you can’t do with a simple MATLAB object The first step toward an improved implementation takes advantage of syntax using subsref and subsasgn After that, the development of a truly robust class requires attention to nearly every detail It has already taken eighteen chapters to discuss all of the details, and we are not yet done C911X_C018.fm Page 27 3 Friday, March 2, 20 07 9:06 AM... comments for each variable The variable data are also provided in Table 18.8 When you are finished, click Done to return to the main dialog C911X_C018.fm Page 26 6 Friday, March 2, 20 07 9:06 AM 26 6 A Guide to MATLAB Object- Oriented Programming FIGURE 18. 12 Class Wizard, cShape public function dialog TABLE 18.7 Public Member Function Field Values Public Function Name Input Argument List Output Argument List... The one-argument constructor is a little odd because Class Wizard always generates a copy constructor When a one-argument constructor is defined, the generated version of ctor_1 uses the specified variable name and still includes a C911X_C018.fm Page 26 5 Friday, March 2, 20 07 9:06 AM Class Wizard Versions of the Shape Hierarchy 26 5 FIGURE 18.11 Class Wizard, cShape constructor function dialog case for... definition for cDiamond, but after all that work, you should probably create a cStar object and draw it If you would prefer to wait for the test drive, that is okay with me C911X_C018.fm Page 27 1 Friday, March 2, 20 07 9:06 AM Class Wizard Versions of the Shape Hierarchy 27 1 18.4 CDIAMOND CLASS WIZARD DEFINITION DATA The definition for cDiamond and cStar are almost the same The difference is that cStar includes . software 21 % A Class Wizard v.3 assembled file, generated: 18-Jan -20 06 13:18:46 C911X_C018.fm Page 25 9 Friday, March 2, 20 07 9:06 AM 26 0 A Guide to MATLAB Object- Oriented Programming 22 % 23 24 . software 25 % A Class Wizard v.3 assembled file, generated: 20 -Dec -20 05 13 :23 :23 26 C911X_C018.fm Page 25 6 Friday, March 2, 20 07 9:06 AM Class Wizard Versions of the Shape Hierarchy 25 7 18.1 .5. 2, 20 07 9:06 AM 25 6 A Guide to MATLAB Object- Oriented Programming only data required are a comma-separated list of input variable names. The function name is created based on the number of variables.

Ngày đăng: 05/08/2014, 21:21

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN