How to resolve the algorithm Object serialization step by step in the Factor programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Object serialization step by step in the Factor programming language
Table of Contents
Problem Statement
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Object serialization step by step in the Factor programming language
Source code in the factor programming language
USING: accessors combinators.extras io io.encodings.binary
io.files io.files.info kernel prettyprint serialize ;
IN: rosetta-code.object-serialization
! Define two classes, item and armor. armor is a subclass of
! item.
TUPLE: item name value ;
TUPLE: armor < item physical-resistance fire-resistance ;
! Define boa constructors for both classes using C: shorthand.
! boa means By Order of Arguments, and yes, this is a pun on boa
! constrictors.
C: <item> item
C: <armor> armor
! Create three example items and print them out
! non-destructively.
"Fish scales" 0.05 <item>
"Gold piece" 1 <item>
"Breastplate of Ashannar" 50,000 55 30 <armor>
[ [ . ] keep ] tri@ nl
! Serialize the three objects to a binary file named
! objects.dat.
"Serializing objects to objects.dat . . . " print
"objects.dat" binary [ [ serialize ] tri@ ] with-file-writer
! Check that objects.dat exists.
"objects.dat exists? " write "objects.dat" exists? .
"Size on disk: " write "objects.dat" file-info size>> pprint
" bytes" print nl
! Deserialize three objects from objects.dat.
"Deserializing objects from objects.dat . . . " print nl
"objects.dat" binary [ [ deserialize ] thrice ] with-file-reader
! Print out deserialized objects.
[ . ] tri@
You may also check:How to resolve the algorithm Table creation/Postal addresses step by step in the PostgreSQL programming language
You may also check:How to resolve the algorithm Linear congruential generator step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Word ladder step by step in the Julia programming language
You may also check:How to resolve the algorithm Ethiopian multiplication step by step in the Wren programming language
You may also check:How to resolve the algorithm Bell numbers step by step in the Pascal programming language