tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
1
Task/Object-serialization/0DESCRIPTION
Normal file
1
Task/Object-serialization/0DESCRIPTION
Normal file
|
|
@ -0,0 +1 @@
|
|||
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.
|
||||
2
Task/Object-serialization/1META.yaml
Normal file
2
Task/Object-serialization/1META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
note: Object oriented
|
||||
29
Task/Object-serialization/ALGOL-68/object-serialization.alg
Normal file
29
Task/Object-serialization/ALGOL-68/object-serialization.alg
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
MODE ENTITY = STRUCT([6]CHAR name, INT creation);
|
||||
FORMAT entity repr = $"Name: "g", Created:"g$;
|
||||
MODE PERSON = STRUCT(ENTITY entity, STRING email);
|
||||
FORMAT person repr = $f(entity repr)", Email: "g$;
|
||||
|
||||
PERSON instance1 := PERSON(ENTITY("Cletus", 20080808), "test+1@localhost.localdomain");
|
||||
print((name OF entity OF instance1, new line));
|
||||
|
||||
ENTITY instance2 := ENTITY("Entity",20111111);
|
||||
print((name OF instance2, new line));
|
||||
|
||||
FILE target;
|
||||
INT errno := open(target, "rows.dat", stand back channel); # open file #
|
||||
|
||||
# Serialise #
|
||||
put(target,(instance1, new line, instance2, new line));
|
||||
printf(($"Serialised..."l$));
|
||||
|
||||
close(target); # flush file stream #
|
||||
errno := open(target, "rows.dat", stand back channel); # load again #
|
||||
|
||||
# Unserialise #
|
||||
PERSON i1;
|
||||
ENTITY i2;
|
||||
get(target,(i1, new line, i2, new line));
|
||||
printf(($"Unserialised..."l$));
|
||||
|
||||
printf((person repr, i1, $l$));
|
||||
printf((entity repr, i2, $l$))
|
||||
25
Task/Object-serialization/Ada/object-serialization-1.ada
Normal file
25
Task/Object-serialization/Ada/object-serialization-1.ada
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
with Ada.Calendar; use Ada.Calendar;
|
||||
|
||||
package Messages is
|
||||
type Message is tagged record
|
||||
Timestamp : Time;
|
||||
end record;
|
||||
|
||||
procedure Print(Item : Message);
|
||||
procedure Display(Item : Message'Class);
|
||||
|
||||
type Sensor_Message is new Message with record
|
||||
Sensor_Id : Integer;
|
||||
Reading : Float;
|
||||
end record;
|
||||
|
||||
procedure Print(Item : Sensor_Message);
|
||||
|
||||
type Control_Message is new Message with record
|
||||
Actuator_Id : Integer;
|
||||
Command : Float;
|
||||
end record;
|
||||
|
||||
procedure Print(Item : Control_Message);
|
||||
|
||||
end Messages;
|
||||
68
Task/Object-serialization/Ada/object-serialization-2.ada
Normal file
68
Task/Object-serialization/Ada/object-serialization-2.ada
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
with Ada.Text_Io; use Ada.Text_Io;
|
||||
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
|
||||
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
|
||||
|
||||
package body Messages is
|
||||
|
||||
-----------
|
||||
-- Print --
|
||||
-----------
|
||||
|
||||
procedure Print (Item : Message) is
|
||||
The_Year : Year_Number;
|
||||
The_Month : Month_Number;
|
||||
The_Day : Day_Number;
|
||||
Seconds : Day_Duration;
|
||||
begin
|
||||
Split(Date => Item.Timestamp, Year => The_Year,
|
||||
Month => The_Month, Day => The_Day, Seconds => Seconds);
|
||||
|
||||
Put("Time Stamp:");
|
||||
Put(Item => The_Year, Width => 4);
|
||||
Put("-");
|
||||
Put(Item => The_Month, Width => 1);
|
||||
Put("-");
|
||||
Put(Item => The_Day, Width => 1);
|
||||
New_Line;
|
||||
end Print;
|
||||
|
||||
-----------
|
||||
-- Print --
|
||||
-----------
|
||||
|
||||
procedure Print (Item : Sensor_Message) is
|
||||
begin
|
||||
Print(Message(Item));
|
||||
Put("Sensor Id: ");
|
||||
Put(Item => Item.Sensor_Id, Width => 1);
|
||||
New_Line;
|
||||
Put("Reading: ");
|
||||
Put(Item => Item.Reading, Fore => 1, Aft => 4, Exp => 0);
|
||||
New_Line;
|
||||
end Print;
|
||||
|
||||
-----------
|
||||
-- Print --
|
||||
-----------
|
||||
|
||||
procedure Print (Item : Control_Message) is
|
||||
begin
|
||||
Print(Message(Item));
|
||||
Put("Actuator Id: ");
|
||||
Put(Item => Item.Actuator_Id, Width => 1);
|
||||
New_Line;
|
||||
Put("Command: ");
|
||||
Put(Item => Item.Command, Fore => 1, Aft => 4, Exp => 0);
|
||||
New_Line;
|
||||
end Print;
|
||||
|
||||
-------------
|
||||
---Display --
|
||||
-------------
|
||||
|
||||
procedure Display(Item : Message'Class) is
|
||||
begin
|
||||
Print(Item);
|
||||
end Display;
|
||||
|
||||
end Messages;
|
||||
40
Task/Object-serialization/Ada/object-serialization-3.ada
Normal file
40
Task/Object-serialization/Ada/object-serialization-3.ada
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
with Messages; use Messages;
|
||||
with Ada.Streams.Stream_Io; use Ada.Streams.Stream_Io;
|
||||
with Ada.Calendar; use Ada.Calendar;
|
||||
with Ada.Text_Io;
|
||||
|
||||
procedure Streams_Example is
|
||||
S1 : Sensor_Message;
|
||||
M1 : Message;
|
||||
C1 : Control_Message;
|
||||
Now : Time := Clock;
|
||||
The_File : Ada.Streams.Stream_Io.File_Type;
|
||||
The_Stream : Ada.Streams.Stream_IO.Stream_Access;
|
||||
begin
|
||||
S1 := (Now, 1234, 0.025);
|
||||
M1.Timestamp := Now;
|
||||
C1 := (Now, 15, 0.334);
|
||||
Display(S1);
|
||||
Display(M1);
|
||||
Display(C1);
|
||||
begin
|
||||
Open(File => The_File, Mode => Out_File,
|
||||
Name => "Messages.dat");
|
||||
exception
|
||||
when others =>
|
||||
Create(File => The_File, Name => "Messages.dat");
|
||||
end;
|
||||
The_Stream := Stream(The_File);
|
||||
Sensor_Message'Class'Output(The_Stream, S1);
|
||||
Message'Class'Output(The_Stream, M1);
|
||||
Control_Message'Class'Output(The_Stream, C1);
|
||||
Close(The_File);
|
||||
Open(File => The_File, Mode => In_File,
|
||||
Name => "Messages.dat");
|
||||
The_Stream := Stream(The_File);
|
||||
Ada.Text_Io.New_Line(2);
|
||||
while not End_Of_File(The_File) loop
|
||||
Display(Message'Class'Input(The_Stream));
|
||||
end loop;
|
||||
Close(The_File);
|
||||
end Streams_Example;
|
||||
118
Task/Object-serialization/C++/object-serialization.cpp
Normal file
118
Task/Object-serialization/C++/object-serialization.cpp
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
#include <string>
|
||||
#include <fstream>
|
||||
#include <boost/serialization/string.hpp>
|
||||
#include <boost/archive/text_oarchive.hpp>
|
||||
#include <boost/archive/text_iarchive.hpp>
|
||||
#include <boost/serialization/base_object.hpp>
|
||||
#include <iostream>
|
||||
|
||||
class Employee {
|
||||
public :
|
||||
Employee( ) { }
|
||||
|
||||
Employee ( const std::string &dep , const std::string &namen )
|
||||
: department( dep ) , name( namen ) {
|
||||
my_id = count++ ;
|
||||
}
|
||||
|
||||
std::string getName( ) const {
|
||||
return name ;
|
||||
}
|
||||
|
||||
std::string getDepartment( ) const {
|
||||
return department ;
|
||||
}
|
||||
|
||||
int getId( ) const {
|
||||
return my_id ;
|
||||
}
|
||||
|
||||
void setDepartment( const std::string &dep ) {
|
||||
department.assign( dep ) ;
|
||||
}
|
||||
|
||||
virtual void print( ) {
|
||||
std::cout << "Name: " << name << '\n' ;
|
||||
std::cout << "Id: " << my_id << '\n' ;
|
||||
std::cout << "Department: " << department << '\n' ;
|
||||
}
|
||||
|
||||
virtual ~Employee( ) { }
|
||||
static int count ;
|
||||
private :
|
||||
std::string name ;
|
||||
std::string department ;
|
||||
int my_id ;
|
||||
friend class boost::serialization::access ;
|
||||
|
||||
template <class Archive>
|
||||
void serialize( Archive &ar, const unsigned int version ) {
|
||||
ar & my_id ;
|
||||
ar & name ;
|
||||
ar & department ;
|
||||
}
|
||||
|
||||
} ;
|
||||
|
||||
class Worker : public Employee {
|
||||
public :
|
||||
Worker( const std::string & dep, const std::string &namen ,
|
||||
double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }
|
||||
|
||||
Worker( ) { }
|
||||
|
||||
double getSalary( ) {
|
||||
return salary ;
|
||||
}
|
||||
|
||||
void setSalary( double pay ) {
|
||||
if ( pay > 0 )
|
||||
salary = pay ;
|
||||
}
|
||||
|
||||
virtual void print( ) {
|
||||
Employee::print( ) ;
|
||||
std::cout << "wage per hour: " << salary << '\n' ;
|
||||
}
|
||||
private :
|
||||
double salary ;
|
||||
friend class boost::serialization::access ;
|
||||
template <class Archive>
|
||||
void serialize ( Archive & ar, const unsigned int version ) {
|
||||
ar & boost::serialization::base_object<Employee>( *this ) ;
|
||||
ar & salary ;
|
||||
}
|
||||
} ;
|
||||
|
||||
int Employee::count = 0 ;
|
||||
|
||||
int main( ) {
|
||||
std::ofstream storefile( "/home/ulrich/objects.dat" ) ; //creating objects of base class
|
||||
const Employee emp1( "maintenance" , "Fritz Schmalstieg" ) ;
|
||||
const Employee emp2( "maintenance" , "John Berry" ) ;
|
||||
const Employee emp3( "repair" , "Pawel Lichatschow" ) ;
|
||||
const Employee emp4( "IT" , "Marian Niculescu" ) ;
|
||||
const Worker worker1( "maintenance" , "Laurent Le Chef" , 20 ) ;//creating objects of derived class
|
||||
const Worker worker2 ( "IT" , "Srinivan Taraman" , 55.35 ) ;
|
||||
boost::archive::text_oarchive oar ( storefile ) ;//starting serialization into designated file
|
||||
oar << emp1 ;
|
||||
oar << emp2 ;
|
||||
oar << emp3 ;
|
||||
oar << emp4 ;
|
||||
oar << worker1 ;
|
||||
oar << worker2 ;
|
||||
storefile.close( ) ;
|
||||
std::cout << "Reading out the data again\n" ;
|
||||
Employee e1 , e2 , e3 , e4 ; //creating instances of base class objects for deserialization
|
||||
Worker w1, w2 ; // same for objects of derived class
|
||||
std::ifstream sourcefile( "/home/ulrich/objects.dat" ) ;
|
||||
boost::archive::text_iarchive iar( sourcefile ) ;//starting deserialization
|
||||
iar >> e1 >> e2 >> e3 >> e4 ;
|
||||
iar >> w1 >> w2 ;
|
||||
sourcefile.close( ) ;
|
||||
std::cout << "And here are the data after deserialization!( abridged):\n" ;
|
||||
e1.print( ) ;
|
||||
e3.print( ) ;
|
||||
w2.print( ) ;
|
||||
return 0 ;
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
(defmacro with-serialization-to-file ((stream pathname) &body body)
|
||||
`(with-open-file (,stream ,pathname
|
||||
:element-type '(unsigned-byte 8)
|
||||
:direction :output
|
||||
:if-exists :supersede)
|
||||
,@body))
|
||||
|
||||
(defclass entity ()
|
||||
((name :initarg :name :initform "Some entity")))
|
||||
|
||||
(defclass person (entity)
|
||||
((name :initarg :name :initform "The Nameless One")))
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
CL-USER> (list (make-instance 'entity)
|
||||
(make-instance 'person))
|
||||
|
||||
(#<ENTITY {1004B13141}> #<PERSON {1004B142B1}>)
|
||||
CL-USER> (mapc #'describe *)
|
||||
#<ENTITY {1004B13141}>
|
||||
[standard-object]
|
||||
|
||||
Slots with :INSTANCE allocation:
|
||||
NAME = "Some entity"
|
||||
#<PERSON {1004B142B1}>
|
||||
[standard-object]
|
||||
|
||||
Slots with :INSTANCE allocation:
|
||||
NAME = "The Nameless One"
|
||||
(#<ENTITY {1004B13141}> #<PERSON {1004B142B1}>)
|
||||
CL-USER> (with-serialization-to-file (stream "/tmp/objects.dat")
|
||||
(cl-serializer:serialize * :output stream)
|
||||
;; SERIALIZE shows an octet-vector as its return value
|
||||
(values))
|
||||
; No value
|
||||
CL-USER> (mapc #'describe (with-open-file (stream "/tmp/objects.dat"
|
||||
:element-type '(unsigned-byte 8))
|
||||
(cl-serializer:deserialize stream)))
|
||||
#<ENTITY {1003C12911}>
|
||||
[standard-object]
|
||||
|
||||
Slots with :INSTANCE allocation:
|
||||
NAME = "Some entity"
|
||||
#<PERSON {1003C12A81}>
|
||||
[standard-object]
|
||||
|
||||
Slots with :INSTANCE allocation:
|
||||
NAME = "The Nameless One"
|
||||
(#<ENTITY {1003C12911}> #<PERSON {1003C12A81}>)
|
||||
35
Task/Object-serialization/D/object-serialization.d
Normal file
35
Task/Object-serialization/D/object-serialization.d
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import test1;
|
||||
import std.stdio;
|
||||
import std.file;
|
||||
class full2:base2 {
|
||||
this(byte[]manip,bool isroot=true) {super(manip,isroot);}
|
||||
this(){super();}
|
||||
void print() {
|
||||
foreach(item;rep) {
|
||||
writefln(item.i32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
full2 base = new full2();
|
||||
base1 tmp = new base1;
|
||||
tmp.i32 = 34;
|
||||
base.add_rep(tmp);
|
||||
tmp = new base1;
|
||||
tmp.i32 = 32;
|
||||
base.add_rep(tmp);
|
||||
tmp = new base1;
|
||||
tmp.i32 = 33;
|
||||
base.add_rep(tmp);
|
||||
tmp = new base1;
|
||||
tmp.i32 = 36;
|
||||
base.add_rep(tmp);
|
||||
writefln("Input data:");
|
||||
base.print;
|
||||
write("objects.dat",base.Serialize());
|
||||
byte[]filedata = cast(byte[])read("objects.dat");
|
||||
base = new full2(filedata);
|
||||
writefln("Output data:");
|
||||
base.print;
|
||||
}
|
||||
21
Task/Object-serialization/E/object-serialization-1.e
Normal file
21
Task/Object-serialization/E/object-serialization-1.e
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
def makeEvent(time :int) {
|
||||
return def event {
|
||||
to __printOn(out) { out.print(`@@$time`) }
|
||||
to __optUncall() { return [makeEvent, "run", [time]] }
|
||||
to getTime() { return time }
|
||||
}
|
||||
}
|
||||
|
||||
def makeArrival(time :int, what :any, position :int) {
|
||||
return def arrival extends makeEvent(time) {
|
||||
to __printOn(out) {
|
||||
out.print(`$what to $position $super`)
|
||||
}
|
||||
to __optUncall() {
|
||||
return [makeArrival, "run", [time, what, position]]
|
||||
}
|
||||
|
||||
to getWhat() { return what }
|
||||
to getPosition() { return position }
|
||||
}
|
||||
}
|
||||
3
Task/Object-serialization/E/object-serialization-2.e
Normal file
3
Task/Object-serialization/E/object-serialization-2.e
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
def surgeon := <import:org.erights.e.elib.serial.makeSurgeon>().diverge()
|
||||
surgeon.addExit(makeEvent, "makeEvent")
|
||||
surgeon.addExit(makeArrival, "makeArrival")
|
||||
6
Task/Object-serialization/E/object-serialization-3.e
Normal file
6
Task/Object-serialization/E/object-serialization-3.e
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
def objs := [makeEvent(timer.now()),
|
||||
makeArrival(timer.now(), "Smith", 7)]
|
||||
|
||||
stdout.println(objs)
|
||||
<file:objects.dat>.setBytes(surgeon.serialize(objs))
|
||||
stdout.println(surgeon.unserialize(<file:objects.dat>.getBytes()))
|
||||
154
Task/Object-serialization/Go/object-serialization.go
Normal file
154
Task/Object-serialization/Go/object-serialization.go
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
type printable interface {
|
||||
print()
|
||||
}
|
||||
|
||||
func main() {
|
||||
// create instances
|
||||
animals := []printable{
|
||||
&Animal{Alive: true},
|
||||
&Cat{},
|
||||
&Lab{
|
||||
Dog: Dog{Animal: Animal{Alive: true}},
|
||||
Color: "yellow",
|
||||
},
|
||||
&Collie{Dog: Dog{
|
||||
Animal: Animal{Alive: true},
|
||||
ObedienceTrained: true,
|
||||
}},
|
||||
}
|
||||
|
||||
// display
|
||||
fmt.Println("created:")
|
||||
for _, a := range animals {
|
||||
a.print()
|
||||
}
|
||||
|
||||
// serialize
|
||||
f, err := os.Create("objects.dat")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
for _, a := range animals {
|
||||
gob.Register(a)
|
||||
}
|
||||
err = gob.NewEncoder(f).Encode(animals)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
f.Close()
|
||||
|
||||
// read
|
||||
f, err = os.Open("objects.dat")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
var clones []printable
|
||||
gob.NewDecoder(f).Decode(&clones)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
// display
|
||||
fmt.Println("\nloaded from objects.dat:")
|
||||
for _, c := range clones {
|
||||
c.print()
|
||||
}
|
||||
}
|
||||
|
||||
type Animal struct {
|
||||
Alive bool
|
||||
}
|
||||
|
||||
func (a *Animal) print() {
|
||||
if a.Alive {
|
||||
fmt.Println(" live animal, unspecified type")
|
||||
} else {
|
||||
fmt.Println(" dead animal, unspecified type")
|
||||
}
|
||||
}
|
||||
|
||||
type Dog struct {
|
||||
Animal
|
||||
ObedienceTrained bool
|
||||
}
|
||||
|
||||
func (d *Dog) print() {
|
||||
switch {
|
||||
case !d.Alive:
|
||||
fmt.Println(" dead dog")
|
||||
case d.ObedienceTrained:
|
||||
fmt.Println(" trained dog")
|
||||
default:
|
||||
fmt.Println(" dog, not trained")
|
||||
}
|
||||
}
|
||||
|
||||
type Cat struct {
|
||||
Animal
|
||||
LitterBoxTrained bool
|
||||
}
|
||||
|
||||
func (c *Cat) print() {
|
||||
switch {
|
||||
case !c.Alive:
|
||||
fmt.Println(" dead cat")
|
||||
case c.LitterBoxTrained:
|
||||
fmt.Println(" litter box trained cat")
|
||||
default:
|
||||
fmt.Println(" cat, not litter box trained")
|
||||
}
|
||||
}
|
||||
|
||||
type Lab struct {
|
||||
Dog
|
||||
Color string
|
||||
}
|
||||
|
||||
func (l *Lab) print() {
|
||||
var r string
|
||||
if l.Color == "" {
|
||||
r = "lab, color unspecified"
|
||||
} else {
|
||||
r = l.Color + " lab"
|
||||
}
|
||||
switch {
|
||||
case !l.Alive:
|
||||
fmt.Println(" dead", r)
|
||||
case l.ObedienceTrained:
|
||||
fmt.Println(" trained", r)
|
||||
default:
|
||||
fmt.Printf(" %s, not trained\n", r)
|
||||
}
|
||||
}
|
||||
|
||||
type Collie struct {
|
||||
Dog
|
||||
CatchesFrisbee bool
|
||||
}
|
||||
|
||||
func (c *Collie) print() {
|
||||
switch {
|
||||
case !c.Alive:
|
||||
fmt.Println(" dead collie")
|
||||
case c.ObedienceTrained && c.CatchesFrisbee:
|
||||
fmt.Println(" trained collie, catches frisbee")
|
||||
case c.ObedienceTrained && !c.CatchesFrisbee:
|
||||
fmt.Println(" trained collie, but doesn't catch frisbee")
|
||||
case !c.ObedienceTrained && c.CatchesFrisbee:
|
||||
fmt.Println(" collie, not trained, but catches frisbee")
|
||||
case !c.ObedienceTrained && !c.CatchesFrisbee:
|
||||
fmt.Println(" collie, not trained, doesn't catch frisbee")
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
class Entity implements Serializable {
|
||||
static final serialVersionUID = 3504465751164822571L
|
||||
String name = 'Thingamabob'
|
||||
public String toString() { return name }
|
||||
}
|
||||
|
||||
class Person extends Entity implements Serializable {
|
||||
static final serialVersionUID = -9170445713373959735L
|
||||
Person() { name = 'Clement' }
|
||||
Person(name) { this.name = name }
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
File objectStore = new File('objectStore.ser')
|
||||
if (objectStore.exists()) { objectStore.delete() }
|
||||
assert ! objectStore.exists()
|
||||
def os
|
||||
try {
|
||||
os = objectStore.newObjectOutputStream()
|
||||
os << new Person()
|
||||
os << 10.5
|
||||
os << new Person('Cletus')
|
||||
os << new Date()
|
||||
os << new Person('Pious')
|
||||
os << java.awt.Color.RED
|
||||
os << new Person('Linus')
|
||||
os << 'just random garbage'
|
||||
os << new Person('Lucy')
|
||||
os << ['lists', 'are', 'serializable']
|
||||
os << new Person('Schroeder')
|
||||
} catch (e) { throw new Exception(e) } finally { os?.close() }
|
||||
assert objectStore.exists()
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
def is
|
||||
try {
|
||||
is = objectStore.newObjectInputStream(this.class.classLoader)
|
||||
is.eachObject { println it }
|
||||
} catch (e) { throw new Exception(e) } finally { is?.close() }
|
||||
|
||||
objectStore.delete()
|
||||
assert ! objectStore.exists()
|
||||
41
Task/Object-serialization/J/object-serialization-1.j
Normal file
41
Task/Object-serialization/J/object-serialization-1.j
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
lin_z_=:5!:5
|
||||
serializeObject=:3 :0
|
||||
p=. copath y
|
||||
d=. ;LF;"1(,'=:';lin__y)"0 nl__y i.4
|
||||
'(',(5!:5<'p'),')(copath[cocurrent@])cocreate ''''',,d,LF
|
||||
)
|
||||
|
||||
deserializeObject=:3 :0
|
||||
o=.conl 1
|
||||
0!:100 y
|
||||
(conl 1)-.o
|
||||
)
|
||||
|
||||
coclass'room'
|
||||
create=:3 :'size=:y'
|
||||
print=:3 :'''room size '',":size'
|
||||
|
||||
coclass'kitchen'
|
||||
coinsert'room'
|
||||
print=:3 :'''kitchen size '',":size'
|
||||
|
||||
coclass'kitchenWithSink'
|
||||
coinsert'kitchen'
|
||||
print=:3 :'''kitchen with sink size '',":size'
|
||||
|
||||
cocurrent'base'
|
||||
|
||||
R=:'small' conew 'room'
|
||||
K=:'medium' conew 'kitchen'
|
||||
S=:'large' conew 'kitchenWithSink'
|
||||
print__R''
|
||||
print__K''
|
||||
print__S''
|
||||
|
||||
|
||||
(;<@serializeObject"0 R,K,S) 1!:2 <'objects.dat'
|
||||
|
||||
'r1 k1 s1'=: <"0 deserializeObject 1!:1<'objects.dat'
|
||||
print__r1''
|
||||
print__k1''
|
||||
print__s1''
|
||||
17
Task/Object-serialization/J/object-serialization-2.j
Normal file
17
Task/Object-serialization/J/object-serialization-2.j
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
print__R''
|
||||
room size small
|
||||
print__K''
|
||||
kitchen size medium
|
||||
print__S''
|
||||
kitchen with sink size large
|
||||
|
||||
|
||||
(;<@serializeObject"0 R,K,S) 1!:2 <'objects.dat'
|
||||
|
||||
'r1 k1 s1'=: <"0 deserializeObject 1!:1<'objects.dat'
|
||||
print__r1''
|
||||
room size small
|
||||
print__k1''
|
||||
kitchen size medium
|
||||
print__s1''
|
||||
kitchen with sink size large
|
||||
60
Task/Object-serialization/Java/object-serialization.java
Normal file
60
Task/Object-serialization/Java/object-serialization.java
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import java.io.*;
|
||||
|
||||
// classes must implement java.io.Serializable in order to be serializable
|
||||
class Entity implements Serializable {
|
||||
// it is recommended to hard-code serialVersionUID so changes to class
|
||||
// will not invalidate previously serialized objects
|
||||
static final long serialVersionUID = 3504465751164822571L;
|
||||
String name = "Entity";
|
||||
public String toString() { return name; }
|
||||
}
|
||||
|
||||
class Person extends Entity implements Serializable {
|
||||
static final long serialVersionUID = -9170445713373959735L;
|
||||
Person() { name = "Cletus"; }
|
||||
}
|
||||
|
||||
public class SerializationTest {
|
||||
public static void main(String[] args) {
|
||||
Person instance1 = new Person();
|
||||
System.out.println(instance1);
|
||||
|
||||
Entity instance2 = new Entity();
|
||||
System.out.println(instance2);
|
||||
|
||||
// Serialize
|
||||
try {
|
||||
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("objects.dat")); // open ObjectOutputStream
|
||||
|
||||
out.writeObject(instance1); // serialize "instance1" and "instance2" to "out"
|
||||
out.writeObject(instance2);
|
||||
out.close();
|
||||
System.out.println("Serialized...");
|
||||
} catch (IOException e) {
|
||||
System.err.println("Something screwed up while serializing");
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
// Deserialize
|
||||
try {
|
||||
ObjectInput in = new ObjectInputStream(new FileInputStream("objects.dat")); // open ObjectInputStream
|
||||
|
||||
Object readObject1 = in.readObject(); // read two objects from "in"
|
||||
Object readObject2 = in.readObject(); // you may want to cast them to the appropriate types
|
||||
in.close();
|
||||
System.out.println("Deserialized...");
|
||||
|
||||
System.out.println(readObject1);
|
||||
System.out.println(readObject2);
|
||||
} catch (IOException e) {
|
||||
System.err.println("Something screwed up while deserializing");
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
} catch (ClassNotFoundException e) {
|
||||
System.err.println("Unknown class for deserialized object");
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
23
Task/Object-serialization/OCaml/object-serialization.ocaml
Normal file
23
Task/Object-serialization/OCaml/object-serialization.ocaml
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
type entity = { name : string }
|
||||
|
||||
let create_entity () = { name = "Entity" }
|
||||
let print_entity x = print_endline x.name
|
||||
let create_person () = { name = "Cletus" }
|
||||
|
||||
let instance1 = create_person ()
|
||||
let instance2 = create_entity ()
|
||||
|
||||
(* Serialize *)
|
||||
let out_chan = open_out_bin "objects.dat";;
|
||||
output_value out_chan instance1;;
|
||||
output_value out_chan instance2;;
|
||||
close_out out_chan;;
|
||||
|
||||
(* Deserialize *)
|
||||
let in_chan = open_in_bin "objects.dat";;
|
||||
let result1 : entity = input_value in_chan;;
|
||||
let result2 : entity = input_value in_chan;;
|
||||
close_in in_chan;;
|
||||
|
||||
print_entity result1;;
|
||||
print_entity result2;;
|
||||
50
Task/Object-serialization/Objeck/object-serialization.objeck
Normal file
50
Task/Object-serialization/Objeck/object-serialization.objeck
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
bundle Default {
|
||||
class Thingy {
|
||||
@id : Int;
|
||||
|
||||
New(id : Int) {
|
||||
@id := id;
|
||||
}
|
||||
|
||||
method : public : Print() ~ Nil {
|
||||
@id->PrintLine();
|
||||
}
|
||||
}
|
||||
|
||||
class Person from Thingy {
|
||||
@name : String;
|
||||
|
||||
New(id : Int, name : String) {
|
||||
Parent(id);
|
||||
@name := name;
|
||||
}
|
||||
|
||||
method : public : Print() ~ Nil {
|
||||
@id->PrintLine();
|
||||
@name->PrintLine();
|
||||
}
|
||||
}
|
||||
|
||||
class Serial {
|
||||
function : Main(args : String[]) ~ Nil {
|
||||
t := Thingy->New(7);
|
||||
p := Person->New(13, "Bush");
|
||||
|
||||
s := IO.Serializer->New();
|
||||
s->Write(t->As(Base));
|
||||
s->Write(p->As(Base));
|
||||
|
||||
writer := IO.FileWriter->New("objects.dat");
|
||||
writer->WriteBuffer(s->Serialize());
|
||||
writer->Close();
|
||||
|
||||
buffer := IO.FileReader->ReadBinaryFile("objects.dat");
|
||||
d := IO.Deserializer->New(buffer);
|
||||
|
||||
t2 := d->ReadObject()->As(Thingy);
|
||||
t2->Print();
|
||||
p2 := d->ReadObject()->As(Person);
|
||||
p2->Print();
|
||||
}
|
||||
}
|
||||
}
|
||||
185
Task/Object-serialization/Objective-C/object-serialization.m
Normal file
185
Task/Object-serialization/Objective-C/object-serialization.m
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
#import <Foundation/Foundation.h>
|
||||
|
||||
// a fantasy two level hierarchy
|
||||
@interface Animal : NSObject <NSCoding>
|
||||
{
|
||||
NSString *animalName;
|
||||
int numberOfLegs;
|
||||
}
|
||||
- (id) initWithName: (NSString*)name andLegs: (NSInteger)legs;
|
||||
- (void) dump;
|
||||
// the following allows "(de)archiving" of the object
|
||||
- (void) encodeWithCoder: (NSCoder*)coder;
|
||||
- (id) initWithCoder: (NSCoder*)coder;
|
||||
@end
|
||||
|
||||
@implementation Animal
|
||||
- (id) initWithName: (NSString*)name andLegs: (NSInteger)legs
|
||||
{
|
||||
if ((self = [super init])) {
|
||||
animalName = [name retain];
|
||||
numberOfLegs = legs;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
- (void) dealloc
|
||||
{
|
||||
[animalName release];
|
||||
[super dealloc];
|
||||
}
|
||||
- (void) dump
|
||||
{
|
||||
NSLog(@"%@ has %d legs", animalName, numberOfLegs);
|
||||
}
|
||||
// ========
|
||||
- (void) encodeWithCoder: (NSCoder*)coder
|
||||
{
|
||||
[coder encodeObject: animalName forKey: @"Animal.name"];
|
||||
[coder encodeInt: numberOfLegs forKey: @"Animal.legs"];
|
||||
}
|
||||
- (id) initWithCoder: (NSCoder*)coder
|
||||
{
|
||||
if ((self = [super init])) {
|
||||
animalName = [[coder decodeObjectForKey: @"Animal.name"] retain];
|
||||
numberOfLegs = [coder decodeIntForKey: @"Animal.legs"];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@end
|
||||
|
||||
@interface Mammal : Animal <NSCoding>
|
||||
{
|
||||
BOOL hasFur;
|
||||
NSMutableArray *eatenList;
|
||||
}
|
||||
- (id) initWithName: (NSString*)name hasFur: (BOOL)fur;
|
||||
- (void) addEatenThing: (NSString*)thing;
|
||||
- (void) dump;
|
||||
// for archiving / dearchiving:
|
||||
- (void) encodeWithCoder: (NSCoder*)coder;
|
||||
- (id) initWithCoder: (NSCoder*)coder;
|
||||
@end
|
||||
|
||||
@implementation Mammal
|
||||
- (id) init
|
||||
{
|
||||
if ((self = [super init])) {
|
||||
hasFur = NO;
|
||||
eatenList = [[NSMutableArray alloc] initWithCapacity: 10];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
- (id) initWithName: (NSString*)name hasFur: (BOOL)fur
|
||||
{
|
||||
if ((self = [super initWithName: name andLegs: 4])) {
|
||||
hasFur = fur;
|
||||
eatenList = [[NSMutableArray alloc] initWithCapacity: 10];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
- (void) addEatenThing: (NSString*)thing
|
||||
{
|
||||
[eatenList addObject: thing];
|
||||
}
|
||||
- (void) dealloc
|
||||
{
|
||||
[eatenList release];
|
||||
[super dealloc];
|
||||
}
|
||||
- (void) dump
|
||||
{
|
||||
[super dump];
|
||||
NSLog(@"has fur? %@", (hasFur) ? @"yes" : @"no" );
|
||||
// fast enum not implemented yet in gcc 4.3, at least
|
||||
// without a patch that it seems to exist...
|
||||
NSEnumerator *en = [eatenList objectEnumerator];
|
||||
id element;
|
||||
NSLog(@"it has eaten %d things:", [eatenList count]);
|
||||
while( (element = [en nextObject]) != nil )
|
||||
NSLog(@"it has eaten a %@", element);
|
||||
NSLog(@"end of eaten things list");
|
||||
}
|
||||
// ========= de/archiving
|
||||
- (void) encodeWithCoder: (NSCoder*)coder
|
||||
{
|
||||
[super encodeWithCoder: coder];
|
||||
[coder encodeBool: numberOfLegs forKey: @"Mammal.hasFur"];
|
||||
[coder encodeObject: eatenList forKey: @"Mammal.eaten"];
|
||||
}
|
||||
- (id) initWithCoder: (NSCoder*)coder
|
||||
{
|
||||
if ((self = [super initWithCoder: coder])) {
|
||||
hasFur = [coder decodeBoolForKey: @"Mammal.hasFur"];
|
||||
eatenList = [[coder decodeObjectForKey: @"Mammal.eaten"] retain];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@end
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
Mammal *aMammal;
|
||||
Animal *anAnimal;
|
||||
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
|
||||
|
||||
// let us create a fantasy animal
|
||||
anAnimal = [[Animal alloc]
|
||||
initWithName: @"Eptohippos"
|
||||
andLegs: 7
|
||||
];
|
||||
// for some reason an Eptohippos is not an horse with 7 legs,
|
||||
// and it is not a mammal, of course...
|
||||
|
||||
// let us create a fantasy mammal (which is an animal too)
|
||||
aMammal = [[Mammal alloc]
|
||||
initWithName: @"Mammaluc"
|
||||
hasFur: YES
|
||||
];
|
||||
// let us add some eaten stuff...
|
||||
[aMammal addEatenThing: @"lamb"];
|
||||
[aMammal addEatenThing: @"table"];
|
||||
[aMammal addEatenThing: @"web page"];
|
||||
|
||||
// dump anAnimal
|
||||
NSLog(@"----- original Animal -----");
|
||||
[anAnimal dump];
|
||||
|
||||
// dump aMammal...
|
||||
NSLog(@"----- original Mammal -----");
|
||||
[aMammal dump];
|
||||
|
||||
// now let us store the objects...
|
||||
NSMutableData *data = [[NSMutableData alloc] init];
|
||||
NSKeyedArchiver *arch = [[NSKeyedArchiver alloc]
|
||||
initForWritingWithMutableData: data];
|
||||
[arch encodeObject: anAnimal forKey: @"Eptohippos"];
|
||||
[arch encodeObject: aMammal forKey: @"Mammaluc"];
|
||||
[anAnimal release];
|
||||
[aMammal release];
|
||||
[arch finishEncoding];
|
||||
[arch release];
|
||||
[data writeToFile: @"objects.dat" atomically: YES];
|
||||
[data release];
|
||||
|
||||
// now we want to retrieve the saved objects...
|
||||
NSData *ldata = [[NSData alloc]
|
||||
initWithContentsOfFile: @"objects.dat"];
|
||||
NSKeyedUnarchived *darch = [[NSKeyedUnarchiver alloc]
|
||||
initForReadingWithData: ldata];
|
||||
Animal *archivedAnimal = [darch decodeObjectForKey: @"Eptohippos"];
|
||||
Mammal *archivedMammal = [darch decodeObjectForKey: @"Mammaluc"];
|
||||
[darch finishDecoding];
|
||||
[ldata release];
|
||||
[darch release];
|
||||
|
||||
// now let's dump/print the objects...
|
||||
NSLog(@"\n");
|
||||
NSLog(@"----- the archived Animal -----");
|
||||
[archivedAnimal dump];
|
||||
NSLog(@"----- the archived Mammal -----");
|
||||
[archivedMammal dump];
|
||||
|
||||
[pool release];
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
2
Task/Object-serialization/PHP/object-serialization.php
Normal file
2
Task/Object-serialization/PHP/object-serialization.php
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
$myObj = new Object();
|
||||
$serializedObj = serialize($myObj);
|
||||
35
Task/Object-serialization/Perl/object-serialization-1.pl
Normal file
35
Task/Object-serialization/Perl/object-serialization-1.pl
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
{
|
||||
package Greeting;
|
||||
sub new {
|
||||
my $v = "Hello world!\n";
|
||||
bless \$v, shift;
|
||||
};
|
||||
sub stringify {
|
||||
${shift()};
|
||||
};
|
||||
};
|
||||
{
|
||||
package Son::of::Greeting;
|
||||
use base qw(Greeting); # inherit methods
|
||||
sub new { # overwrite method of super class
|
||||
my $v = "Hello world from Junior!\n";
|
||||
bless \$v, shift;
|
||||
};
|
||||
};
|
||||
{
|
||||
use Storable qw(store retrieve);
|
||||
package main;
|
||||
my $g1 = Greeting->new;
|
||||
my $s1 = Son::of::Greeting->new;
|
||||
print $g1->stringify;
|
||||
print $s1->stringify;
|
||||
|
||||
store $g1, 'objects.dat';
|
||||
my $g2 = retrieve 'objects.dat';
|
||||
|
||||
store $s1, 'objects.dat';
|
||||
my $s2 = retrieve 'objects.dat';
|
||||
|
||||
print $g2->stringify;
|
||||
print $s2->stringify;
|
||||
};
|
||||
25
Task/Object-serialization/Perl/object-serialization-2.pl
Normal file
25
Task/Object-serialization/Perl/object-serialization-2.pl
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
use MooseX::Declare;
|
||||
|
||||
class Greeting {
|
||||
use MooseX::Storage;
|
||||
with Storage('format' => 'JSON', io => 'File');
|
||||
has string => (is => 'ro', default => "Hello world!\n");
|
||||
}
|
||||
class Son::Of::Greeting extends Greeting {
|
||||
has string => (is => 'ro', default => "Hello from Junior!\n");
|
||||
}
|
||||
|
||||
my $g1 = Greeting->new;
|
||||
my $s1 = Son::Of::Greeting->new;
|
||||
|
||||
print $g1->string;
|
||||
print $s1->string;
|
||||
|
||||
$g1->store('object1.json');
|
||||
my $g2 = Greeting->load('object1.json');
|
||||
|
||||
$s1->store('object2.json');
|
||||
my $s2 = Son::Of::Greeting->load('object2.json');
|
||||
|
||||
print $g2->string;
|
||||
print $s2->string;
|
||||
30
Task/Object-serialization/PicoLisp/object-serialization-1.l
Normal file
30
Task/Object-serialization/PicoLisp/object-serialization-1.l
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
(class +Point)
|
||||
# x y
|
||||
|
||||
(dm T (X Y)
|
||||
(=: x (or X 0))
|
||||
(=: y (or Y 0)) )
|
||||
|
||||
(dm print> ()
|
||||
(prinl "Point " (: x) "," (: y)) )
|
||||
|
||||
(class +Circle +Point)
|
||||
# r
|
||||
|
||||
(dm T (X Y R)
|
||||
(super X Y)
|
||||
(=: r (or R 0)) )
|
||||
|
||||
(dm print> ()
|
||||
(prinl "Circle " (: x) "," (: y) "," (: r)) )
|
||||
|
||||
(setq
|
||||
P (new '(+Point) 3 4)
|
||||
C (new '(+Circle) 10 10 5) )
|
||||
|
||||
(print> P)
|
||||
(print> C)
|
||||
|
||||
(out "objects.dat"
|
||||
(pr (val P) (getl P))
|
||||
(pr (val C) (getl C)) )
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
(in "objects.dat"
|
||||
(putl (setq A (box (rd))) (rd))
|
||||
(putl (setq B (box (rd))) (rd)) )
|
||||
|
||||
(print> A)
|
||||
(print> B)
|
||||
37
Task/Object-serialization/Python/object-serialization.py
Normal file
37
Task/Object-serialization/Python/object-serialization.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
# Object Serialization in Python
|
||||
# serialization in python is accomplished via the Pickle module.
|
||||
# Alternatively, one can use the cPickle module if speed is the key,
|
||||
# everything else in this example remains the same.
|
||||
|
||||
import pickle
|
||||
|
||||
class Entity:
|
||||
def __init__(self):
|
||||
self.name = "Entity"
|
||||
def printName(self):
|
||||
print self.name
|
||||
|
||||
class Person(Entity): #OldMan inherits from Entity
|
||||
def __init__(self): #override constructor
|
||||
self.name = "Cletus"
|
||||
|
||||
instance1 = Person()
|
||||
instance1.printName()
|
||||
|
||||
instance2 = Entity()
|
||||
instance2.printName()
|
||||
|
||||
target = file("objects.dat", "w") # open file
|
||||
|
||||
# Serialize
|
||||
pickle.dump((instance1, instance2), target) # serialize `instance1` and `instance2`to `target`
|
||||
target.close() # flush file stream
|
||||
print "Serialized..."
|
||||
|
||||
# Unserialize
|
||||
target = file("objects.dat") # load again
|
||||
i1, i2 = pickle.load(target)
|
||||
print "Unserialized..."
|
||||
|
||||
i1.printName()
|
||||
i2.printName()
|
||||
70
Task/Object-serialization/Ruby/object-serialization.rb
Normal file
70
Task/Object-serialization/Ruby/object-serialization.rb
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
class Being
|
||||
def initialize(specialty=nil)
|
||||
@specialty=specialty
|
||||
end
|
||||
def to_s
|
||||
"(object_id = #{object_id})\n"+"(#{self.class}):".ljust(12)+to_s4Being+(@specialty ? "\n"+" "*12+@specialty : "")
|
||||
end
|
||||
def to_s4Being
|
||||
"I am a collection of cooperative molecules with a talent for self-preservation."
|
||||
end
|
||||
end
|
||||
|
||||
class Earthling < Being
|
||||
def to_s4Being
|
||||
"I originate from a blue planet.\n"+" "*12+to_s4Earthling
|
||||
end
|
||||
end
|
||||
|
||||
class Mammal < Earthling
|
||||
def initialize(type)
|
||||
@type=type
|
||||
end
|
||||
def to_s4Earthling
|
||||
"I am champion in taking care of my offspring and eating everything I can find, except mammals of type #{@type}."
|
||||
end
|
||||
end
|
||||
|
||||
class Fish < Earthling
|
||||
def initialize(iq)
|
||||
@iq=(iq>1 ? :instrustableValue : iq)
|
||||
end
|
||||
def to_s4Earthling
|
||||
"Although I think I can think, I can't resist biting in hooks."
|
||||
end
|
||||
end
|
||||
|
||||
class Moonling < Being
|
||||
def to_s4Being
|
||||
"My name is Janneke Maan, and apparently some Earthlings will pay me a visit."
|
||||
end
|
||||
end
|
||||
|
||||
diverseCollection=[]
|
||||
diverseCollection << (marsian=Being.new("I come from Mars and like playing hide and seek."))
|
||||
diverseCollection << (me=Mammal.new(:human))
|
||||
diverseCollection << (nemo=Fish.new(0.99))
|
||||
diverseCollection << (jannakeMaan=Moonling.new)
|
||||
|
||||
puts "BEGIN ORIGINAL DIVERSE COLLECTION"
|
||||
diverseCollection.each do |being|
|
||||
puts "",being.to_s
|
||||
end
|
||||
puts "END ORIGINAL DIVERSE COLLECTION"
|
||||
puts "\n"+"*"*50+"\n\n"
|
||||
|
||||
#Marshal the diverse Array of beings
|
||||
File.open('diverseCollection.bin','w') do |fo|
|
||||
fo << Marshal.dump(diverseCollection)
|
||||
end
|
||||
|
||||
#load the Array of diverse beings
|
||||
sameDiverseCollection=Marshal.load(File.read('diverseCollection.bin'))
|
||||
|
||||
puts "BEGIN LOADED DIVERSE COLLECTION"
|
||||
puts(
|
||||
sameDiverseCollection.collect do |being|
|
||||
being.to_s
|
||||
end.join("\n\n")
|
||||
)
|
||||
puts "END LOADED DIVERSE COLLECTION"
|
||||
52
Task/Object-serialization/Tcl/object-serialization.tcl
Normal file
52
Task/Object-serialization/Tcl/object-serialization.tcl
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
package require Tcl 8.6
|
||||
package require TclOO::serializer 0.1
|
||||
|
||||
# These classes are inspired by the Perl example
|
||||
oo::class create Greeting {
|
||||
superclass oo::serializable
|
||||
variable v
|
||||
constructor {} {
|
||||
set v "Hello world!"
|
||||
}
|
||||
method get {} {
|
||||
return $v
|
||||
}
|
||||
}
|
||||
oo::class create SubGreeting {
|
||||
superclass Greeting oo::serializable
|
||||
variable v
|
||||
constructor {} {
|
||||
set v "Hello world from Junior!"
|
||||
}
|
||||
}
|
||||
oo::class create GreetingsHolder {
|
||||
superclass oo::serializable
|
||||
variable o1 o2
|
||||
constructor {greeting1 greeting2} {
|
||||
set o1 $greeting1
|
||||
set o2 $greeting2
|
||||
}
|
||||
method printGreetings {} {
|
||||
puts [$o1 get]
|
||||
puts [$o2 get]
|
||||
}
|
||||
destructor {
|
||||
$o1 destroy
|
||||
$o2 destroy
|
||||
}
|
||||
}
|
||||
|
||||
# Make some objects and store them
|
||||
GreetingsHolder create holder [Greeting new] [SubGreeting new]
|
||||
set f [open "objects.dat" w]
|
||||
puts $f [oo::serialize holder]
|
||||
close $f
|
||||
|
||||
# Delete the objects
|
||||
holder destroy
|
||||
|
||||
# Recreate the objects from the file and show that they work
|
||||
set f [open "objects.dat" r]
|
||||
set obj [oo::deserialize [read $f]]
|
||||
close $f
|
||||
$obj printGreetings
|
||||
Loading…
Add table
Add a link
Reference in a new issue