There are many proposals for the ecological role of restriction-modification (RM) systems, and why they would exist on mobile genetic elements (e.g. plasmids and viruses). In this case, I am specifically talking about the viruses that infect bacteria (aka, bacteriophage).
1) RM systems may have an anti-viral function. Normally we would think of such systems as being part of the host chromosome, but as Alan Boyd suggested, once a temperate phage has integrated itself into the chromosome, its fitness is tied to its host. Therefore, a RM system found in a prophage could prevent infections by additional phage. See here for a discussion of this issue:
http://www.ncbi.nlm.nih.gov/pubmed/23471617
2) RM systems may have "addictive" properties by acting as toxin-antitoxin systems. Basically, this means that if the genes for the RM system are lost, the host cell dies. This can provide selection for the maintenance of plasmids and prophage inside of the host cell. See here for a discussion of this issue:
http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3874152/
3) Finally, viruses need to destroy the host genome -- both to suppress any anti-viral response and to release nutrients for viral replication. While this is typically achieved with nucleases other than restriction endonucleases, there is at least one situation where a RE seems to be involved. This is discussed in the first link above (see the section entitled "Role in Nutrition")